使用DI和InstanceContextMode.Percall定制ServiceHost

时间:2013-06-04 14:05:06

标签: c# wcf servicehost

在我的托管应用程序中,我目前将我的WCF服务运行为:

SomeService service = new SomeService(container) //IUnityContainer
ServiceHost serviceHost = new ServiceHost(service, serviceAddress);

捕获的是什么? SomeService定义为:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single

这不再好了,我需要将它设为 InstanceContextMode.PerCall

尝试.Open()时如果将InstanceContextMode更改为“PerCall” - 它会抛出:

System.InvalidOperationException: In order to use one of the ServiceHost constructors that takes a service instance, the InstanceContextMode of the service must be set to InstanceContextMode.Single.  This can be configured via the ServiceBehaviorAttribute.  Otherwise, please consider using the ServiceHost constructors that take a Type argument

这是解决我问题的方法吗? How do I pass values to the constructor on my wcf service?

我的主要关注点:
我在这个托管应用程序中运行不同类型的服务,似乎这个解决方案只有在我运行一种类型的服务时才是好的。

1 个答案:

答案 0 :(得分:3)

当需要多个服务实例(PerCall或PerSession)时,将单个服务实例传递到ServiceHost是不够的......这是例外。

控制实例创建由IInstanceProvider管理。

  

这是解决我问题的方法吗? How do I pass values to the constructor on my wcf service?

这只回答了你问题的一半。您正在使用Unity。创建容器的管理需要成为实现的一部分。最常见的解决方案是使用Unity.WCF,它也可用作NuGet包。

请注意,Unity.WCF不支持基于WCF OperationContexts的对象生存期。有许多(更复杂的)实现,如this