.net - 通过 web.config 对 WCF 服务的 Unity 依赖注入(inject)

标签 .net wcf dependency-injection web-config unity-container

我有一个项目,我正在尝试使用 DI。我正在使用 Unity,对于正常的装配和注入(inject)来说,一切似乎都运行良好。

我正在尝试进一步打破与 WCF 服务的依赖关系。我要注入(inject)的 WCF 服务是在运行时创建的,目前没有使用 DI,而且我不使用 VS .net 生成的代理:

MyService = new ChannelFactory<IMyService>("BasicHttpBinding_IMyService").CreateChannel();

上面的端点在 web.config 中:

<endpoint address="http://localhost:35806/MyService.svc"
       binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyService"
       contract="Interfaces.IMyService" name="BasicHttpBinding_IMyService" />

我想弄清楚如何通过 web.config 将此 WCF 服务映射到接口(interface),以便我可以使用构造函数注入(inject)

在 web.config 中,法线映射使用“mapTo”发生,您可以在其中指定接口(interface)别名和您之前定义的类的别名。

<type type="IMyService" mapTo="MyService">
 <lifetime type="singleton"/>
</type>

由于 WCF 服务代理是在运行时动态创建的,因此我没有对“MyService”类的引用,而是需要从服务的 “BasicHttpBinding_IMyService” 端点中提取。

关于如何实现这一点有什么想法吗?

最佳答案

我从配置文件中看到这个工作的唯一方法是创建一个实现 IMyService 的 MyService 类 - 在幕后它创建自己的 Channel(使用 ChannelFactory 代码片段)并且基本上充当代理。

但与其这样,为什么不直接调用

RegisterInstance<IMyService>(myServiceChannelInstance)

在你的统一容器上并传入一个已经创建的 MyService channel 实例?

关于.net - 通过 web.config 对 WCF 服务的 Unity 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2066490/

相关文章:

.net - 为什么在设计器中为控件的属性指定数值会导致代码中出现 new Decimal(new int[] {... ?

.net - PHP 与 .NET JSON Web 服务

java - HK2中如何将多个接口(interface)收集到一个Collection中?

php - 拉维尔 5 : Type-hinting a FormRequest class inside a controller that extends from BaseController

asp.net - IControllerFactory 'MyWebSite.WebUI.Infrastructure.NinjectControllerFactory' 没有返回名称为 'Admin' 的 Controller

c# - IList 和 IEnumerable 上的扩展方法是否具有相同的名称?

.net - Windows Server 2012 中的 WPF 应用程序中的颜色错误

java - Web 服务与 WCF

WCF 4 : Fileless Activation Fails On XP (IIS 5) that has SSL port enabled

c# - 使用 Directory.GetFiles 时出现 UnauthorizedAccessException