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

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

我正在使用simpleInjector,当我尝试调用simpleInjectorServiceHostfactory->createServiceHost(类型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处理这一问题的方式的误解。

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

我在Github上为此创建了一个问题。

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

因为在这种情况下,WCF将回调容器以创建类型,而SimpleInjector OffCourse可以处理构造函数中的参数。

一个可能的解决方法是将服务配置为Percall,并假设您希望对某些缓存使用单个缓存,则将WCF实现中的缓存重构为其自己的类,并将其注册为简单注入器中的单个实例。


您必须有一个默认的构造函数,这是WCF服务创建实例所调用的。您可以使用自己的InstanceProvider来接管这个过程,并注入您需要的东西。

如果您使用的是singleton(single),那么servicehost需要传递一个已经创建的实例(可以使用任何类型的构造函数创建)。我不确定您的DI-FX如何构造这种实例。请参阅此答案wcf concurrencyMode single和instanceContextMode percall。