使用DI和InstanceContextMode.Percall自定义ServiceHost

本文关键字:自定义 ServiceHost Percall InstanceContextMode DI 使用 | 更新日期: 2023-09-27 18:16:56

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

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

有什么隐情?

定义的someeservice
[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

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

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

使用DI和InstanceContextMode.Percall自定义ServiceHost

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

控制实例的创建由IInstanceProvider管理。

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

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

注意Unity。WCF不支持基于WCF OperationContexts的对象生命周期。有许多(更复杂的)这样的实现。