Tuesday, 5 April 2011

WCF tutorial part 03 - setting endpoints inside app.config file

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.

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));
 Console.WriteLine("The service is ready.");
 Console.WriteLine("Press <ENTER> to terminate service.");

...catches etc.
Add App.config file to WCFHost project
Put this into this file:
<?xml version="1.0" encoding="utf-8" ?>
              <behavior name="Metadata">
                <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8000/meta" />
            <service behaviorConfiguration="Metadata" name="MyService.Service">
                <endpoint address="net.tcp://localhost:9000/tcp" binding="netTcpBinding"
                    contract="MyService.IService" listenUriMode="Explicit" />
First I'm adding Metadata behavior, it's almost equal to putting this in code:
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
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.

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:

No comments:

Post a Comment