In this part I'm going to show you how to set endpoints inside app.config file instead of heaving them in code. This way we can easily change them in the future without need to recompile our application.
Host
From Program.cs file remove line with
baseAddress definition, also change
ServiceHost construction to following
ServiceHost serviceHost = new ServiceHost(typeof(MyService.Service));
our Program.cs file Main method will start with
ServiceHost serviceHost = new ServiceHost(typeof(MyService.Service));
try
{
serviceHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.ReadLine();
serviceHost.Close();
}
...catches etc.
Add
App.config file to
WCFHost project
Put this into this file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="Metadata">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8000/meta" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="Metadata" name="MyService.Service">
<endpoint address="net.tcp://localhost:9000/tcp" binding="netTcpBinding"
contract="MyService.IService" listenUriMode="Explicit" />
</service>
</services>
</system.serviceModel>
</configuration>
First I'm adding Metadata behavior, it's almost equal to putting this in code:
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
serviceHost.Description.Behaviors.Add(smb);
I'm also specifying where will be metadata available (
http://localhost:8000/meta)
Then I'm creating new tcp endpoint at address
net.tcp://localhost:9000/tcp.
Client
Now we need to recofigure our client. Service reference cannot be updated since metadata location has changed. First, start your host project (remember setting startup project mode to current selection). If the host is up, right click on
ServiceReference and choose
Configure Service Reference...
If you receive error similiar to this one:
remove your service reference completely and add new service reference.
In both cases as new address enter
http://localhost:8000/meta . Service should have been discovered (click Go):
If it's discovered correct Namespace to ServiceReference and click OK.
Start you're client - it should connect to the host without any further changes needed.
You can download source code from here:
http://sites.google.com/site/terespl/files/WCFTutorialpart03.zip