这是我对这个问题的解决方案(我不是 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));
}