Reputation: 3959
I have multiple WCF Services hosted in IIS and configured with 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>
Service Implementations
public class ServiceA : IServiceA
{
public ServiceA()
{
}
}
public class ServiceB : IServiceB
{
public ServiceB()
{
}
}
public class ServiceC : IServiceC
{
public ServiceC(IServiceA serviceA)
{
}
}
As you can see, ServiceC is different from the others and need an implementation of IServiceA. Autofac can't resolve it, because there is no registration for IServiceA.
So I change the registration to this:
builder.RegisterType<ServiceA>().As<IServiceA>();
Autofac can now resolve ServiceC successfully, but the WCF hosting is not working anymore:
An exception of type 'System.ServiceModel.ServiceActivationException' occurred in mscorlib.dll but was not handled in user code
So my question is:
Is there a way that I can have both, a hosted WCF Service instance, and the possibility to pass a Service Implementation to another Service? All configured with AutoFac? I'm also thinking of a workaround, but everything that comes to my mind results in a huge effort. I know that these services needs to be refactored, so that there is no need to pass in another "service". But this is a different story.
Upvotes: 3
Views: 1081
Reputation: 246998
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>();
//...
This will associate the class and interface together so that IServiceA
can be injected as needed and it will be resolved to ServiceA
. This also allow the WCF to not break as ServiceA
is registered.
Reference Autofac Documentation: Registration Concepts
Upvotes: 3