3 回答
TA贡献1982条经验 获得超2个赞
WCF支持构造函数注入,但是您必须跳过几个步骤才能到达那里。关键在于编写自定义ServiceHostFactory。尽管它也必须具有默认构造函数,但是您可以使用它构造所有正确的行为。
作为示例,我最近写了一篇使用Castle Windsor来为服务实现连接依赖关系的示例。CreateServiceHost的实现只是这样做:
return new WindsorServiceHost(this.container, serviceType, baseAddresses);
this.container配置的IWindsorContainer 在哪里。
WindsorServiceHost看起来像这样:
public class WindsorServiceHost : ServiceHost
{
public WindsorServiceHost(IWindsorContainer container, Type serviceType, params Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
foreach (var cd in this.ImplementedContracts.Values)
{
cd.Behaviors.Add(new WindsorInstanceProvider(container));
}
}
}
和WindsorInstanceProvider看起来像这样:
public class WindsorInstanceProvider : IInstanceProvider, IContractBehavior
{
private readonly IWindsorContainer container;
public WindsorInstanceProvider(IWindsorContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
#region IInstanceProvider Members
public object GetInstance(InstanceContext instanceContext, Message message)
{
return this.GetInstance(instanceContext);
}
public object GetInstance(InstanceContext instanceContext)
{
var serviceType = instanceContext.Host.Description.ServiceType;
return this.container.Resolve(serviceType);
}
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
this.container.Release(instance);
}
#endregion
#region IContractBehavior Members
public void AddBindingParameters(ContractDescription contractDescription, ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ContractDescription contractDescription, ServiceEndpoint endpoint, DispatchRuntime dispatchRuntime)
{
dispatchRuntime.InstanceProvider = this;
}
public void Validate(ContractDescription contractDescription, ServiceEndpoint endpoint)
{
}
#endregion
}
这看起来可能很多,但是请注意,它是可重用的通用代码,其循环复杂度较低。
您可以遵循相同的编码习惯,使用另一个DI容器或使用穷人的DI来实现依赖注入。
- 3 回答
- 0 关注
- 603 浏览
添加回答
举报