[英]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托管不再有效:
mscorlib.dll中出現“System.ServiceModel.ServiceActivationException”類型的異常,但未在用戶代碼中處理
所以我的問題是:
有沒有辦法可以同時擁有一個托管的WCF服務實例,以及將服務實現傳遞給另一個服務的可能性? 全部配置了AutoFac? 我也在想一個解決方法,但是我想到的一切都會帶來巨大的努力。 我知道這些服務需要重構,因此不需要傳遞另一個“服務”。 但這是一個不同的故事。
如果要將組件公開為一組服務以及使用默認服務,請使用
AsSelf
方法:
//...
builder.RegisterType<ServiceA>()
.AsSelf() //<--
.As<IServiceA>();
//...
這會將類和接口關聯在一起,以便可以根據需要注入IServiceA
,並將其解析為ServiceA
。 這也允許WCF在ServiceA
注冊時不會中斷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.