Software    csharp

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:

    RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class TestService
    [Description("Test Description.")]
    [WebGet(UriTemplate = "go")]
    public string Test()
        return "hi2u";

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

IUserRepository userRepo;

public TestService(IUserRepository userRepo)
    this.userRepo = userRepo;

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:

public NinjectWebServiceHostFactory()
    _kernel = NinjectKernel.Instance.Kernel; // point to your kernel

You can then create the binding like so

routes.Add(new ServiceRoute("api/v1/test",
    new NinjectServiceHostFactory(), typeof(TestService)));

BAM! Web service host with Ninject.

comments powered by Disqus