我在 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
时不会中断。
关于c# - 如何使用 Autofac 将 WCF 服务实现注入(inject)到另一个 WCF 服务中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56614644/