WebServiceHost vs ServiceHost

WCF in .NET Fx 3.5 introduces several types that simplify the creation of services that use the protocols of the web (read REST/Syndication/JSON). Among these are two hosting types: WebServiceHost and WebScriptServiceHostFactory. These types serve the same function as the ServiceHost and ServiceHostFactory type, but they are tailored for the web. For example, WebServiceHost automatically adds the right behavior and does some error checking to ensure http is the transport. Likewise, the WebScriptServiceHostFactory does similar error checking and adds a behavior that sets up the JSON messaging stack.

The WebScriptServiceHostFactory means that developers can setup an .svc file with no config (via directives), and the WebServiceHost means that web developers do not have to muck about with WCF behaviors.

These types automate with work one would otherwise have to do with the ServiceHost type. If, for some reason, you do not want to or cannot use these new types, you can always use the ServiceHost.

The code below shows how to expose a REST endpoint with both the ServiceHost and the WebServiceHost types:

 

 sealed class Program : ISomeContract {

    static void Main(string[] args) {
        
        Uri baseAddress = new Uri("https://localhost:8000");

        HostWithServiceHost(baseAddress);

        HostWithWebServiceHost(baseAddress);
    }

    private static void HostWithServiceHost(Uri baseAddress) {
        
        ServiceHost host = new ServiceHost(typeof(Program), baseAddress);
        WebHttpBinding binding = new WebHttpBinding();

        ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(ISomeContract), binding, "ServiceHost");
        WebHttpBehavior httpBehavior = new WebHttpBehavior();
        endpoint.Behaviors.Add(httpBehavior);

        host.Open();

        Console.WriteLine(@"go to https://localhost:8000/ServiceHost/SomeOperation to test");
        Console.ReadLine();

    }

    private static void HostWithWebServiceHost(Uri baseAddress) {
        
        WebServiceHost host = new WebServiceHost(typeof(Program), baseAddress);
        WebHttpBinding binding = new WebHttpBinding();
        host.AddServiceEndpoint(typeof(ISomeContract), binding, "WebServiceHost");
        host.Open();

        Console.WriteLine(@"go to https://localhost:8000/WebServiceHost/SomeOperation to test");
        Console.ReadLine();
        host.Close();
    
    }

    public String SomeOperation(String input) {
    
        String reply = "You said: " + input;
        Console.WriteLine(reply);
        return reply;
    
    }
}

[ServiceContract]
interface ISomeContract {
    [OperationContract]
    [WebGet(UriTemplate="SomeOperation/{input}")]
    String SomeOperation(String input);
}