自托管WCF:自动创建服务主机并使用Autofac启用依赖项注入 [英] Self-hosted WCF: automatically create service hosts and enable dependency injection with Autofac

查看:159
本文介绍了自托管WCF:自动创建服务主机并使用Autofac启用依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有许多自托管WCF服务的Windows服务.我正在使用Autofac进行DI/IoC.

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

WCF服务和端点是在app.config中设置的,并且通过枚举已配置的服务,Windows服务是能够为每个配置的WCF服务自动创建并打开ServiceHost.

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.

要启用依赖项注入,我向AddDependencyInjectionBehavior( docs )方法用于每个ServiceHost的新实例,但是该方法专门要求一个 contractType ,此时,我仅具有服务实现类型.

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.

可以通过使用反射查找已实现的接口来检索合同类型,但是由于这是我与Autofac合作的第一个项目,因此我想确保自己不会犯错.

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?

感谢您的任何投入.

推荐答案

您可以尝试枚举ServiceHost的所有端点,然后从中提取ContractType.

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

这篇关于自托管WCF:自动创建服务主机并使用Autofac启用依赖项注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆