问题
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