我想对我的自定义 ServiceHostFactory
进行单元测试.不幸的是,我得到了这个 InvalidOperationException
调用CreateServiceHost
时:
'ServiceHostFactory.CreateServiceHost' cannot be invoked within the current hosting environment. This API requires that the calling application be hosted in IIS or WAS.
我可以通过重构我的类来解决这个问题,以便它公开一个可以由单元测试直接调用的公共(public)方法,而不是使用其继承的公共(public)接口(interface);我讨厌仅仅为了单元测试而改变我的界面。我还看到另一个建议生成 Cassini 主机的 SO 答案,但我不想以这种方式使我的单元测试复杂化。
有没有办法解决这个问题
ServiceHostFactory
限制而不诉诸这些措施?
最佳答案
我弄清楚了这个问题。在我的自定义 ServiceHostFactory
,我只覆盖了 protected 方法,CreateServiceHost(Type serviceType, Uri[] baseAddresses)
.通过覆盖公共(public) CreateServiceHost(string constructorString, Uri[] baseAddresses)
方法,我能够毫无问题地构建服务主机工厂。
前:
public class MyServiceHostFactory : ServiceHostFactory
{
protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
{
// ...
}
}
后:
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)
{
// ...
}
}
关于wcf - 在单元测试中托管 WCF 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11565610/