我有一个统一容器:
var unityContainer = new UnityContainer();
配置如下:
unityContainer.RegisterType<IExampleDomainService, ExampleDomainService>();
unityContainer.RegisterType<IExampleWebService, ExampleWebService>();
ExampleWebService
类型及其构造函数如下所示:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class ExampleWebService
{
public ExampleWebService(IExampleDomainService exampleDomainService)
{
this.exampleDomainService = exampleDomainService;
}
// ...
和
ExampleDomainService
没有定义构造函数(当我为该类型显式定义无参数构造函数时,问题也是一样的)。
接下来,如Unity.Wcf中所述
documentation
:
如果您在Windows服务中使用
ServiceHost
,更换
服务宿主
自定义的实例
Unity.Wcf.UnityServiceHost
。您会发现
UnityServiceHost
将Unity容器作为其第一个参数,但在其他方面与默认值相同
服务宿主
.
我执行以下操作:
var host = new UnityServiceHost(unityContainer, typeof(ExampleWebService), baseAddress);
然而,这会引发
System.InvalidOperationException
并显示以下消息:
提供的服务类型无法作为服务加载,因为它没有默认(无参数)构造函数。要解决此问题,请向类型添加默认构造函数,或将该类型的实例传递给主机。
正在查看
UnityServiceHost
implementation at GitHub
它通过给定
serviceType
(
typeof(ExampleWebService)
在这种情况下)直接发送到WCF的本机
服务宿主
:
public sealed class UnityServiceHost : ServiceHost
{
public UnityServiceHost(IUnityContainer container, Type serviceType, params Uri[] baseAddresses)
: base(serviceType, baseAddresses)
^^^^^^^^^^^
???????????
它显然崩溃了,因为
服务宿主
对Unity及其容器一无所知,当缺少无参数构造函数时无法处理。
就是团结。对于非WAS/非IIS托管,我完全崩溃了,或者(我希望)我做了完全错误的事情?