c# - 如何使用 Autofac 将 WCF 服务实现注入(inject)到另一个 WCF 服务中

标签 c# wcf dependency-injection 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? 我也在考虑一种解决方法,但我想到的一切都需要付出巨大的努力。 我知道这些服务需要重构,这样就不需要再传入另一个“服务”了。但这是一个不同的故事。

最佳答案

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>();

//...

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

引用 Autofac Documentation: Registration Concepts

关于c# - 如何使用 Autofac 将 WCF 服务实现注入(inject)到另一个 WCF 服务中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56614644/

相关文章:

c# - 防止未使用的属性从对象传递的最佳方法

java - DI 容器与工厂

c# - 如何在 Ninject 中绑定(bind)通用类型接口(interface)

使用 Lombok 和 Guice 注入(inject)进行 Java 链继承

c# - 获取本地机器上安装的所有证书

c# - 访问 Adob​​e 打印首选项输出文件夹

c# - 检查 Razor 页面中的登录用户角色

c# - 事件处理程序中抛出的 WPF 异常被吞噬了吗?

WCF 未绑定(bind)到正确的 IP 地址

windows-services - 为什么我的托管 WCF 服务的 Windows 服务不能在 LocalService 或 NetworkService 帐户下运行