WCF Essentials—Programmatic Endpoint Configuration


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

WCF Essentials

© 2007 O'Reilly Media

Programmatic Endpoint Configuration

Programmatic endpoint configuration is equivalent to administrative configuration. Instead of resorting to a config file, you rely on programmatic calls to add endpoints to the ServiceHost instance. Again, these calls are always outside the scope of the service code. ServiceHost provides overloaded versions of the AddServiceEndpoint( ) method:

public class ServiceHost 
   : ServiceHostBase
{
   public ServiceEndpoint 
      AddServiceEndpoint(Type implementedContract,
      Binding binding, 
      string address);
    //Additional members
}

You can provide AddServiceEndpoint( ) methods with either relative or absolute addresses, just as with a config file. Example 1-9 demonstrates programmatic configuration of the same endpoints as in Example 1-7.

Example 1-9. Service-side programmatic endpoint configuration

ServiceHost host = new ServiceHost(typeof(MyService));
Binding wsBinding = new WSHttpBinding( );
Binding tcpBinding = new NetTcpBinding( );
host.AddServiceEndpoint(typeof(IMyContract),wsBinding,
   "http://localhost:8000/MyService");
host.AddServiceEndpoint(typeof(IMyContract),tcpBinding,
   "net.tcp://localhost:8001/MyService");
host.AddServiceEndpoint(typeof(IMyOtherContract),tcpBinding,
   "net.tcp://localhost:8002/MyService");
host.Open( );

When you add an endpoint programmatically, the address is given as a string, the contract as a Type, and the binding as one of the subclasses of the abstract class Binding, such as:

public class NetTcpBinding : Binding,...
{...}

To rely on the host base address, provide an empty string if you want to use the base address, or just the URI to use the base address plus the URI:

Uri tcpBaseAddress = new Uri("net.tcp://localhost:8000/");
 
ServiceHost host = new ServiceHost(typeof(MyService),tcpBaseAddress);
 
Binding tcpBinding = new NetTcpBinding( );
 
//Use base address as address
host.AddServiceEndpoint(typeof(IMyContract),tcpBinding,"");
//Add relative address
host.AddServiceEndpoint(typeof(IMyContract),tcpBinding,"MyService");
//Ignore base address
host.AddServiceEndpoint(typeof(IMyContract),tcpBinding,
   "net.tcp://localhost:8001/MyService");
 
host.Open( );

As with administrative configuration using a config file, the host must provide a matching base address; otherwise, an exception occurs. In fact, there is no difference between programmatic and administrative configuration. When you use a config file, all WCF does is parse the file and execute the appropriate programmatic calls in its place.


Previous_Page_.gif Next_Page_.gif

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