這是我解決這個問題(我不是100%肯定我們是否應該這樣做)。
在單元測試夾具的建立,建立一個託管環境(NUnit的例子):
[TestFixtureSetUp]
public void TestFixtureSetup()
{
if(!HostingEnvironment.IsHosted)
{
// The instance constructor hooks up the singleton hosting environment, ewww...
new HostingEnvironment();
// Check the hosting environment is fully initialized
ServiceHostingEnvironment.EnsureInitialized();
}
}
那麼你應當可以自由使用自定義ServiceHostFactory
從單元測試中:
[Test]
public void ServiceHostIsCorrect()
{
// Arrange
var serviceType = typeof (string);
var factory = new UnityServiceHostFactory();
// Act
var serviceHost = factory.CreateServiceHost(serviceType.AssemblyQualifiedName, new Uri[] {});
// Assert
Expect(serviceHost, Is.TypeOf<UnityServiceHost>());
var unityServiceHost = (UnityServiceHost)serviceHost;
Expect(unityServiceHost.Description.ServiceType, Is.EqualTo(serviceType));
}