Self-hosted WCF: automatically create service hosts and enable dependency injection with Autofac
Asked Answered
B

1

0

I'm working on a Windows Service with a number of self-hosted WCF services. I'm using Autofac for DI/IoC.

WCF services and endpoints are set up in app.config, and by enumerating the configured services, the Windows service is able to automatically create and open a ServiceHost for each configured WCF service.

To enable dependency injection, I add a call to the AddDependencyInjectionBehavior (docs) method for each new instance of ServiceHost, but the method specifically requests a contractType and at this point I only have the service implementation type.

I could retrieve the contract type by looking for implemented interfaces using reflection, but since this is my first project working with Autofac, I wanted to make sure I'm not going about this all wrong.

Is there an elegant solution to this, is any of this considered bad practice, or is reflection the only way to go in this case?

Any input is appreciated.

Brooder answered 24/5, 2013 at 16:31 Comment(0)
S
1

You can try to enumerate all endpoints for your ServiceHost, and extract ContractType from there.

ServiceHost host = ...
foreach (ServiceEndpoint endpoint in host.Description.Endpoints)
{
  var contract = endpoint.Contract;
  Type t = contract.ContractType;

  host.AddDependencyInjectionBehavior(t, container);
}
Shoreless answered 25/5, 2013 at 21:18 Comment(1)
Have you actually used this code with more than one endpoint? It fails for me because the AddDependencyInjectionBehavior extension method resolves to adding an AutofacDependencyInjectionServiceBehavior to the ServiceDescription.Behaviors property of the ServiceHost, and that collection does not allow duplicates (even if the properties are different, which is the intent here). See my issue detailed at How to register two WCF service contracts with autofac.Wenona

© 2022 - 2024 — McMap. All rights reserved.