简体   繁体   中英

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

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.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM