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

十年热恋 提交于 2019-12-25 05:32:41

问题


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.


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


来源:https://stackoverflow.com/questions/16739682/self-hosted-wcf-automatically-create-service-hosts-and-enable-dependency-inject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!