如何使用autofac注册两个WCF服务合同

Mic*_*ens 10 c# wcf dependency-injection autofac

我有一个WCF服务,实现了两个服务合同......

public class MyService : IService1, IService2
Run Code Online (Sandbox Code Playgroud)

我自我托管服务......

host = new ServiceHost(typeof(MyService));
Run Code Online (Sandbox Code Playgroud)

当服务只实现一个服务合同时,一切都工作正常,但是当我尝试设置autofac以便像这样注册时:

host.AddDependencyInjectionBehavior<IService1>(_container);
host.AddDependencyInjectionBehavior<IService2>(_container);
Run Code Online (Sandbox Code Playgroud)

...它在第二个引发异常,报告:

该值无法添加到集合中,因为该集合已包含相同类型的项:'Autofac.Integration.Wcf.AutofacDependencyInjectionServiceBehavior'.此集合仅支持每种类型的一个实例.

乍一看,我认为这是说我的两个合同在某种程度上被视为相同的类型,但在二读时我相信它是说AutofacDependencyInjectionServiceBehavior是有问题的类型,即我不能使用它两次!

然而,我发现这篇文章明确地显示了以稍微不同的形式多次使用它:

foreach (var endpoint in host.Description.Endpoints)
{
  var contract = endpoint.Contract;
  Type t = contract.ContractType;
  host.AddDependencyInjectionBehavior(t, container);
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这给出了相同的错误消息.

是否可以在一项服务上注册多个服务合同,如果是,如何?

nem*_*esv 7

实际上,您可以使用Autofac为单个主机注册多个端点.

确实,您无法添加多个,AutofacDependencyInjectionServiceBehavior但此行为会遍历所有端点并在ApplyDispatchBehavior方法中注册它们:source

为了完成这项工作,您需要注册您的服务 AsSelf()

builder.RegisterType<MyService>();
Run Code Online (Sandbox Code Playgroud)

然后您可以正常配置端点:

host = new ServiceHost(typeof(MyService));
host.AddServiceEndpoint(typeof(IService1), binding, string.Empty);
host.AddServiceEndpoint(typeof(IService2), binding, string.Empty);
Run Code Online (Sandbox Code Playgroud)

最后你需要调用AddDependencyInjectionBehaviorsevicehost类型本身:

host.AddDependencyInjectionBehavior<MyService>(container);
Run Code Online (Sandbox Code Playgroud)

这是一个小示例项目(基于文档),演示了这种行为.