使用unity注入WCF代理客户端
本文关键字:代理 客户端 WCF 注入 unity 使用 | 更新日期: 2023-09-27 18:15:15
我有一个asp.net mvc应用程序,需要在其中调用wcf服务。我在项目中添加了服务参考。我使用unity进行依赖注入,想要注入wcf客户端。但由于System.ServiceModel.ClientBase的存在,事情就没那么简单了。我是这样做的。
这是一个自动生成的代理:
public partial class WcfServiceClient :
System.ServiceModel.ClientBase<WcfUnity.IWcfServiceClient>,
WcfUnity.IWcfServiceClient
{
//autogenerated constructors and methods
}
我创建了接口:
public interface ISimpleProxy : WcfUnity.IWcfServiceClient
{
//duplication of methods' signatures
void CloseConnection();
}
我使用部分类扩展了WcfServiceClient:
public partial class WcfServiceClient : ISimpleProxy
{
public void CloseConnection()
{
try
{
Close();
}
catch (Exception)
{
Abort();
}
}
}
然后像这样注射:
container.RegisterType<ISimpleProxy>(new InjectionFactory(c => new WcfServiceClient()));
所以我没有依赖于ClientBase和没有wcf的东西里面的类使用这个wcf代理。这个解决方案有缺点吗?
不,它没有,我使用(大多数)相同的方法。
我建议您让您的接口继承自IDisposable
,因为底层的ClientBase<T>
是一次性的。这样你就不需要CloseConnection
了