Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register two WCF service contracts with autofac

I have a WCF service that implements two service contracts...

public class MyService : IService1, IService2

and I am self-hosting the service...

host = new ServiceHost(typeof(MyService));

Everything was working fine when the service implemented only one service contract, but when I attempt to set up autofac to register both like this:

host.AddDependencyInjectionBehavior<IService1>(_container);
host.AddDependencyInjectionBehavior<IService2>(_container);

... it throws an exception on the second one, reporting:

The value could not be added to the collection, as the collection already contains an item of the same type: 'Autofac.Integration.Wcf.AutofacDependencyInjectionServiceBehavior'. This collection only supports one instance of each type.

At first glance I thought this was saying my two contracts were somehow being seen as the same type but on second reading I believe it is saying that the AutofacDependencyInjectionServiceBehavior is the type in question, i.e. I cannot use it twice!

And yet, I found this post that explicitly showed using it multiple times in a slightly different form:

foreach (var endpoint in host.Description.Endpoints)
{
  var contract = endpoint.Contract;
  Type t = contract.ContractType;
  host.AddDependencyInjectionBehavior(t, container);
}

Unfortunately, that gave the very same error message.

Is it possible to register more than one service contract on one service and, if so, how?

like image 729
Michael Sorens Avatar asked Aug 07 '13 21:08

Michael Sorens


1 Answers

In fact you can register multiple endpoint for a single host with Autofac.

That is true that you cannot add multiple AutofacDependencyInjectionServiceBehavior but this behaviour iterates through all the endpoints and registers them in the ApplyDispatchBehavior method: source

In order to make this work you need to register your service AsSelf()

builder.RegisterType<MyService>();

Then you can configure your endpoint normally:

host = new ServiceHost(typeof(MyService));
host.AddServiceEndpoint(typeof(IService1), binding, string.Empty);
host.AddServiceEndpoint(typeof(IService2), binding, string.Empty);

And finally you need to call the AddDependencyInjectionBehavior with the sevicehost type itself:

host.AddDependencyInjectionBehavior<MyService>(container);

Here is a small sample project (based on the documentation) which demonstrates this behavior.

like image 51
nemesv Avatar answered Oct 20 '22 02:10

nemesv