如何在没有默认无参数构造函数的情况下为单个 WCF 服务注入参数

How to inject parameters for a Single WCF Service without the default parameter-less constructor

我正在使用 SimpleInjector,当我尝试调用 SimpleInjectorServiceHostFactory-->CreateServiceHost(Type serviceType, Uri[] baseAddresses) 时出现以下错误。此错误仅针对标记为 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 的 WCF 服务出现。

The service type provided could not be loaded as a service because it does not have a default (parameter-less) constructor. To fix the problem, add a default constructor to the type, or pass an instance of the type to the host.

对于标记为 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 的服务,即使服务没有默认值,SimpleInjectorServiceHostFactory-->CreateServiceHost(Type serviceType, Uri[] baseAddresses) 方法也能完美运行无参数构造函数。

知道如何为 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] 服务注入参数,就像 [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 服务没有默认值一样无参数构造函数 ?

谢谢

您必须有一个默认构造函数,WCF 服务调用它来创建您的实例。您可以使用自己的 IInstanceProvider 接管此过程并注入您需要的内容。

如果您使用单例 (Single),则 ServiceHost 期望您传递一个已创建的实例(您可以使用任何类型的构造函数创建该实例)。我不确定你的 DI fx 对构建这种实例做了什么。也请参阅此答案 WCF ConcurrencyMode Single and InstanceContextMode PerCall

经过一些挖掘后,我发现这是简单注入器中的一个错误,或者至少是 WCF 处理此问题的方式中的一个错误解释。

ServiceHost class 在其构造函数中需要单例对象而不是类型。如果提供了类型,ServiceHost 将尝试创建实例,因此它需要一个默认构造函数。

为此,我在 GitHub 上创建了一个 issue

but why this default constructor is not required for the "PerCall" WCF Service

因为在那种情况下,WCF 将回调到容器中以创建类型,而 Simple Injector offcourse 可以处理构造函数中的参数。

一个可能的解决方法是确实将您的服务配置为 PerCall 并假设您想要 Single 进行某些缓存,将缓存从 WCF 实现重构到它自己的 class 中并将其注册为 Simple 中的单例注射器.