如何使用 Autofac 将 WCF 服务实现注入到另一个 WCF 服务中

How to inject WCF Service Implementation into another WCF Service with Autofac

我在 IIS 中托管了多个 WCF 服务并配置了 Autofac。

Global.asax

var builder = new ContainerBuilder();

builder.RegisterType<ServiceA>();
builder.RegisterType<ServiceB>();
builder.RegisterType<ServiceC>();

var container = builder.Build();
AutofacHostFactory.Container = container;

web.config

<system.serviceModel>
  ...
  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
    <serviceActivations>
      <add service="ServiceA, MyServicesAssembly" relativeAddress="./ServiceA.svc" factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" />
      <add service="ServiceB, MyServicesAssembly" relativeAddress="./ServiceB.svc" factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" />
      <add service="ServiceC, MyServicesAssembly" relativeAddress="./ServiceC.svc" factory="Autofac.Integration.Wcf.AutofacServiceHostFactory, Autofac.Integration.Wcf" />
    </serviceActivations>
  </serviceHostingEnvironment>
<system.serviceModel>

服务实施

public class ServiceA : IServiceA 
{
    public ServiceA()
    {            
    }
}

public class ServiceB : IServiceB
{
    public ServiceB()
    {            
    }
}

public class ServiceC : IServiceC
{
    public ServiceC(IServiceA serviceA)
    {            
    }
}

如您所见,ServiceC 与其他服务不同,需要 IServiceA 的实现。 Autofac无法解析,因为没有注册IServiceA。

所以我把注册改成这样:

builder.RegisterType<ServiceA>().As<IServiceA>();

Autofac 现在可以成功解析 ServiceC,但 WCF 托管不再工作:

An exception of type 'System.ServiceModel.ServiceActivationException' occurred in mscorlib.dll but was not handled in user code

所以我的问题是:

有没有一种方法可以让我同时拥有托管的 WCF 服务实例和将服务实现传递给另一个服务的可能性?全部配置了 AutoFac? 我也在考虑一种解决方法,但我想到的一切都需要付出巨大的努力。 我知道这些服务需要重构,这样就不需要再传入一个"service"。但这是一个不同的故事。

If you want to expose a component as a set of services as well as using the default service, use the AsSelf method:

//...

builder.RegisterType<ServiceA>()
    .AsSelf() //<--
    .As<IServiceA>();

//...

这会将 class 和接口关联在一起,以便可以根据需要注入 IServiceA 并将其解析为 ServiceA。这也允许 WCF 在注册 ServiceA 时不会中断。

引用Autofac Documentation: Registration Concepts