
Specifying the Host’s ABC’s in Code
Recall that the host is not required to make use of a configuration file to allow the ServiceHost type to build
the server-side plumbing. Everything that can be specified within a *.config file can be hardcoded in the host
directly. Although this does lessen the flexibility of your code base, one possible advantage is you can
obfuscate the compiled host, keeping endpoint locations more secure.
Recall that each binding type has a corresponding class type in the System.ServiceModel namespace.
Consider the following Main() method, which specifies the ABC’s in code (shown in C#; the VB code would
be similar). In this case, you would no longer need a server-side *.config file.
// C# (VB code would be similar)
static void Main(string[] args)
{
using (ServiceHost myServiceHost = new
ServiceHost(typeof(WcfMathService.MyCalc)))
{
// The ABC’s in code!
Uri address = new Uri("http://localhost:8080/MyCalc");
WSHttpBinding binding = new WSHttpBinding();
Type contract = typeof(IBasicMath);
// Add this endpoint.
myServiceHost.AddServiceEndpoint(contract, binding, address);
myServiceHost.Open();
Console.WriteLine("Hit Enter to shut down host");
// Just to keep the host alive.
Console.ReadLine();
}
}
On a related note, if you prefer a strongly typed host, you could create custom class that extends the
ServiceHost type. Your custom type would typically define a two-argument constructor to receive the
contract and ‘base addresses’, which will be defined later in this chapter. The custom ServiceHost would then
override OnOpening() to create the desired endpoint.
// C# code (VB code would be similar).
public class MathServiceHost : ServiceHost
{
public MathServiceHost(Type serviceType, params Uri[] baseAddresses)
:base(serviceType, baseAddresses) {}
protected override void OnOpening()
{
// Specify ABC’s here.
}
}
At this point, the host could make direct use of the MathServiceHost type and would not need to define the
ABC’s directly, as these are encapsulated by the ServiceHost-derived type. Again, most WCF hosts would
not be assembled this way, as the ABC’s have been hardcoded, which makes changing bindings more complex.
Given these points, this class will prefer the use of *.config files where possible.
Specifying the Host ABCs in Code
Table of Contents
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an
online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
Courseware
Training Resources
Tutorials
Services