Hosting a WCF service in a unit test

unit-testing, wcf

Solution

I figured out the issue. In my custom `ServiceHostFactory`, I had only overridden the protected method, `CreateServiceHost(Type serviceType, Uri[] baseAddresses)`. By overriding the public `CreateServiceHost(string constructorString, Uri[] baseAddresses)` method, I was able to construct the service host factory with no issues.

Before:

public class MyServiceHostFactory : ServiceHostFactory
{
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        // ...
    }
}

After:

public class MyServiceHostFactory : ServiceHostFactory
{
    public override ServiceHostBase CreateServiceHost(string constructorString, Uri[] baseAddresses)
    {
        return this.CreateServiceHost(typeof(MyService), baseAddresses);
    }

    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        // ...
    }
}

Problem

I'm wanting to unit test my custom `ServiceHostFactory`. Unfortunately, I get this `InvalidOperationException` when calling `CreateServiceHost`: 'ServiceHostFactory.CreateServiceHost' cannot be invoked within the current hosting environment. This API requires that the calling application be hosted in IIS or WAS. I can work around this by refactoring my class such that it exposes a public method that can be directly invoked by the unit test instead of using its inherited public interface; I hate to change my interface just for the sake of a unit test. I also see another SO answer that recommends spawning a Cassini host, but I'd hate to complicate my unit tests in this manner. Is there a way to work around this `ServiceHostFactory` limitation without resorting to these measures?

Original source