如何将值传递给WCF服务的构造函数?我希望将值传递给实现我的服务的类的构造函数。但是Servicehost只允许我传递要创建的类型的名称,而不是传递给其构造函数的参数。我希望能够传递一个创建我的服务对象的工厂。到目前为止,我发现的是:WCF依赖注入行为这比我想要的更多,而且似乎对我的需求过于复杂。
3 回答
万千封印
TA贡献1891条经验 获得超3个赞
ServiceHostFactory
, ServiceHost
IInstanceProvider
.
public MyService(IDependency dep)
public class MyServiceHostFactory : ServiceHostFactory{ private readonly IDependency dep; public MyServiceHostFactory() { this.dep = new MyClass(); } protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses) { return new MyServiceHost(this.dep, serviceType, baseAddresses); }}public class MyServiceHost : ServiceHost{ public MyServiceHost(IDependency dep, Type serviceType, params Uri[] baseAddresses) : base(serviceType, baseAddresses) { if (dep == null) { throw new ArgumentNullException("dep"); } foreach (var cd in this.ImplementedContracts.Values) { cd.Behaviors.Add(new MyInstanceProvider(dep)); } }}public class MyInstanceProvider : IInstanceProvider, IContractBehavior{ private readonly IDependency dep; public MyInstanceProvider(IDependency dep) { if (dep == null) { throw new ArgumentNullException("dep"); } this.dep = dep; } #region IInstanceProvider Members public object GetInstance(InstanceContext instanceContext, Message message) { return this.GetInstance(instanceContext); } public object GetInstance(InstanceContext instanceContext) { return new MyService(this.dep); } public void ReleaseInstance(InstanceContext instanceContext, object instance) { var disposable = instance as IDisposable; if (disposable != null) { disposable.Dispose(); } } #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}
白衣染霜花
TA贡献1796条经验 获得超10个赞
MyInstanceProviderBehaviorAttribute
Attribute
IServiceBehavior
IServiceBehavior.ApplyDispatchBehavior
// YourInstanceProvider implements IInstanceProvidervar instanceProvider = new YourInstanceProvider(<yourargs>); foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers){ foreach (var epDispatcher in dispatcher.Endpoints) { // this registers your custom IInstanceProvider epDispatcher.DispatchRuntime.InstanceProvider = instanceProvider; }}
[ServiceBehavior][MyInstanceProviderBehavior(<params as you want>)]public class MyService : IMyContract
添加回答
举报
0/150
提交
取消