具有 DI 和 InstanceContextMode.Percall 的自定义 ServiceHost

ila*_*sch 5 c# wcf servicehost

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

SomeService service = new SomeService(container) //IUnityContainer
ServiceHost serviceHost = new ServiceHost(service, serviceAddress);
Run Code Online (Sandbox Code Playgroud)

有什么问题吗?SomeService 定义为:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single
Run Code Online (Sandbox Code Playgroud)

这不再好了,我需要将其设为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
Run Code Online (Sandbox Code Playgroud)

这是我的问题的解决方案吗?如何将值传递给 wcf 服务上的构造函数?

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

Ern*_*ieL 3

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

\n\n

控制实例创建由IInstanceProvider管理。

\n\n
\n

这是我的问题的解决方案吗?如何将值传递给 wcf 服务上的构造函数?

\n
\n\n

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

\n\n

请注意,Unity.WCF 不\xe2\x80\x99t 支持基于 WCF OperationContext 的对象生命周期。有多种(更复杂的)类似的实现

\n