WCF Essentials—Self-hosting and base addresses


Jump to: navigation, search
Visual C# Tutorials
.NET Framework Tutorials

WCF Essentials

© 2007 O'Reilly Media

Self-hosting and base addresses

You can launch a service host without providing any base address by omitting the base addresses altogether:

public static void Main( )
{
   ServiceHost host = new ServiceHost(typeof(MyService));
   host.Open( );
   Application.Run(new MyForm( ));
   host.Close( );
}
Do not provide a null instead of an empty list, because that will throw an exception:
ServiceHost host;
host = new ServiceHost
   (typeof(MyService),null);

You can also register multiple base addresses separated by a comma, as long as the addresses do not use the same transport schema, as in the following snippet (note the use of the params qualifier in Example 1-3):

Uri tcpBaseAddress = new Uri("net.tcp://localhost:8001/");
Uri httpBaseAddress = new Uri("http://localhost:8002/");
ServiceHost host = new ServiceHost(typeof(MyService),
   tcpBaseAddress,httpBaseAddress);

WCF lets you also list the base addresses in the host config file:

<system.serviceModel>
  <services>
    <service name = "MyNamespace.MyService">
      <host>
        <baseAddresses>
          <add baseAddress = "net.tcp://localhost:8001/"/>
          <add baseAddress = "http://localhost:8002/"/>
        </baseAddresses>
      </host>
      ...
    </service>
  </services>
</system.serviceModel>

When you create the host, it will use whichever base address it finds in the config file, plus any base address you provide programmatically. Take extra care to ensure the configured base addresses and the programmatic ones do not overlap in the schema.

You can even register multiple hosts for the same type as long as the hosts use different base addresses:

Uri baseAddress1 = new Uri("net.tcp://localhost:8001/");
ServiceHost host1 = new ServiceHost(typeof(MyService),baseAddress1);
host1.Open( );
 
Uri baseAddress2 = new Uri("net.tcp://localhost:8002/");
ServiceHost host2 = new ServiceHost(typeof(MyService),baseAddress2);
host2.Open( );

However, with the exception of some threading issues discussed in Chapter 8, opening multiple hosts this way offers no real advantage. In addition, opening multiple hosts for the same type does not work with base addresses supplied in the config file and requires use of the ServiceHost constructor.


Previous_Page_.gif Next_Page_.gif

Share this page
  • del.icio.us
  • Facebook
  • Google+
  • StumbleUpon