Ninject with WCF REST Services

I love Ninject, but I was having a terrible issue where I couldn’t get it working with WCF Restful services. After a ton of googling and piecing stuff together I came up with a solution like the following.

I have a test service like this:

I then found if I added items to the constructor I would get service errors normally:

Dustin found a project that extended wcf for Ninject. Unfortunately, it still wasn’t working on account of me needing WebServiceHostFactories instead of ServiceHost factories. You can change the inheritance of the needed files to the web versions (:ServiceHostFactory to WebServiceHostFactory). Here are the files you will need:

  • NinjectInstanceProvider.cs
  • NinjectServiceBehavior.cs
  • NinjectServiceHost.cs
  • NinjectServiceHostFactory.cs

From there just change the instances of NinjectServiceHostFactory to inherit from WebServiceHostFactory instead of ServiceHostFactory. Do the same for NinjectServiceHost (to WebServiceHost). I then removed all the logging (because I was using a small subset of the library).

You will then point your NinjectWebServiceHostFactory class to the location of your kernel:

You can then create the binding like so

BAM! Web service host with Ninject.