Search code examples
c#wcfinversion-of-controlsimple-injector

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


I'm using SimpleInjector and I get the following error when I try to call SimpleInjectorServiceHostFactory-->CreateServiceHost(Type serviceType, Uri[] baseAddresses). This error appear only for the WCF services marked as [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)].

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.

For the services marked as [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] the SimpleInjectorServiceHostFactory-->CreateServiceHost(Type serviceType, Uri[] baseAddresses) method works perfectly even if the service doesn't have a default parameter-less constructor.

Any idea how to have an injection of the parameters for [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] services just like it happens with [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] services without the default parameter-less constructor ?

Thanks


Solution

  • After some digging I found that this is a bug in Simple Injector, or at least a misinterpretation in the way WCF handles this.

    The ServiceHost class needs the singleton object in its ctor instead of the type. If the type is supplied the ServiceHost will try to create the instance and it therefore needs a default constructor.

    I created a issue on GitHub for this.

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

    Because in that case WCF will call back into the container for creating the type and Simple Injector offcourse can handle the parameters in the constructor.

    A possible workaround would be to indeed configure your service as PerCall and assuming you want Single for some caching, refactor the cache out of the WCF implementation into its own class and register this as a singleton in Simple Injector.