当我在我的解决方案中新建一个WCF服务时,我可以执行以下操作,有一个带参数的构造函数可以传入吗?如果是,运行时如何,何时以及在何处填写我所需的IBusinessLogic对象?
[ServiceContract]
public interface IServiceContract
{
[OperationContract]
...
}
public class MyService : IServiceContract
{
IBusinessLogic _businessLogic;
public ServiceLayer(IBusinessLogic businessLogic)
{
_businessLogic = businessLogic;
}
...
}
答案 0 :(得分:13)
开箱即用WCF只会使用默认构造函数,不能使用参数化构造函数。你必须做一些额外的工作才能使WCF调用参数化构造函数。
你可以试试这个:
答案 1 :(得分:6)
答案 2 :(得分:6)
您可以让WCF(间接地)调用非默认构造函数,为此,您需要滚动自己的实例提供程序。您需要实现IInstanceProvider并添加自定义服务行为。一些链接将向您展示如何与Spring.NET结合使用:
答案 3 :(得分:4)
除了其他响应之外,另一种情况是创建单例服务时 - 这是将服务实例传递给ServiceHost(而不是类型);
显然,在创建实例时,您可以使用任何构造函数;
此方法需要向您的服务添加属性:[ServiceBehavior(InstanceContextMode.Single)];
答案 4 :(得分:3)
我将@Mark Seemann的解决方案解释为通用实例提供程序行为。
var host = new ServiceHost(typeof(MyService), baseAddress);
var instanceProvider = new InstanceProviderBehavior<T>(() => new MyService(businessLogic));
instanceProvider.AddToAllContracts(host);
public class InstanceProviderBehavior<T> : IInstanceProvider, IContractBehavior
where T : class
{
private readonly Func<T> m_instanceProvider;
public InstanceProviderBehavior(Func<T> instanceProvider)
{
m_instanceProvider = instanceProvider;
}
// I think this method is more suitable to be an extension method of ServiceHost.
// I put it here in order to simplify the code.
public void AddToAllContracts(ServiceHost serviceHost)
{
foreach (var endpoint in serviceHost.Description.Endpoints)
{
endpoint.Contract.Behaviors.Add(this);
}
}
#region IInstanceProvider Members
public object GetInstance(InstanceContext instanceContext, Message message)
{
return this.GetInstance(instanceContext);
}
public object GetInstance(InstanceContext instanceContext)
{
// Create a new instance of T
return m_instanceProvider.Invoke();
}
public void ReleaseInstance(InstanceContext instanceContext, object instance)
{
try
{
var disposable = instance as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
catch { }
}
#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
}
答案 5 :(得分:2)
您必须实现IInstanceProvider才能调用参数化服务构造函数。这个构造函数在生成的代理中不可用。