Sunday, January 4, 2009

Hosting Wcf Services on a Shared Hosting Plan

Hosting Wcf Services on a windows shared hosting plan has one issue that people should be aware of: You can only add one address per scheme to a service host. But what does this mean?

Shared hosting plans often run with the default IIS set up, which means that there are two addresses to your site: and Wcf only allows one address of any scheme (ie http://) to be used as a Service host, but by default, it tries to add the two. If you would try to run a web service using this markup,

<%@ ServiceHost Language="C#" Debug="true" Service="SomeService" %>

You would receive the following error:

This collection already contains an address with scheme http.  There can be at most one address per scheme in this collection.

To get around this, you'll have to make a custom ServiceHostFactory that will select only one address, and have your markup use this custom factory with the 'Factory' attribute. Which address you prefer is up to you, just remember to use it in your Endpoint configurations!

.svc file:

<%@ ServiceHost Language="C#" Debug="true" Service="SomeService" Factory="SomeNamspace.AddressSelectorHostFactory" %>


AddressSelectorHostFactory.cs file:

public class AddressSelectorHostFactory : ServiceHostFactory
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        // When hosting on a shared hosting plan, the default IIS configuration passes 2 addresses
        // to CreateServiceHost: and
        // You can only add ONE address of a certain scheme (ie: http://), so we just take the www address.

if (baseAddresses.Length > 1)
            Uri address = (from u in baseAddresses where u.AbsoluteUri.StartsWith("http://www.") select u).First();
            return new ServiceHost(serviceType, address);
            return new ServiceHost(serviceType, baseAddresses[0]);


More about this can be read here.

1 comment:

Vargo said...

This is a helpful bit of information, but it doesn't say anything about how to actually host a service on your shared plan.