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?
I figured out the issue. In my custom
ServiceHostFactory, I had only overridden the protected method,CreateServiceHost(Type serviceType, Uri[] baseAddresses). By overriding the publicCreateServiceHost(string constructorString, Uri[] baseAddresses)method, I was able to construct the service host factory with no issues.Before:
After: