Mike
Mike

Reputation: 2922

How can I use Ninject WCF extension with a singleton service?

I'm using Ninject 2.2.1.4 and Ninject.Extensions.Wcf 2.2.0.4.

My service is decorated with the following attribute:

 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

Using the above attribute, I receive the error:

"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."

If I remove the attribute Ninject works as expected.

After doing some research it's my understanding that since the service is marked as a singleton it will automatically be created with a parameter-less constructor by the ServiceHost, hence the error message. In order to resolve the issue, I have to create the service object myself, resolved using ninject, and then pass that singleton object off to the ServiceHost to use. I'm not sure how to do that.

I looked at the WCF extension source and I see that NinjectServiceHost inherits from ServiceHost, so my thought was to bind NinjectServiceHost to my instance of the service object using the overloaded constructor:

 public NinjectServiceHost( object singletonInstance )
        : base( singletonInstance )
    {
    }

I'm not sure if that's correct and if it is, how and where to properly bind it so the ServiceHost can be fed my instance.

Any suggestions? Thanks.

Upvotes: 2

Views: 530

Answers (1)

Remo Gloor
Remo Gloor

Reputation: 32725

If you can live with a beta Version I suggest to update to 2.3.x It supports IIS hosted singleton Services. See also the examples on github

Upvotes: 1

Related Questions