CRM Development

Solutionist has designed the architecture for a new CRM system for use in the medical imaging industry.

Wednesday, 1 February 2012

More .NET IoC - Using Ninject in WCF Services

I've seen other postings about this, but thought I'd add my own 2p-worth since I had to struggle a bit to get it working.

The basic idea is to use Ninject in the WCF pipeline and get WCF use Ninject to create the service. Then you can take advantage of Ninject's IoC to manage dependencies.

I used the base Ninject and the Ninject Web and Wcf extensions - all available via NuGet.

To integrate ninject into the WCF service pipeline, create a "normal" WCF service but add the following to the .svc file

Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" 


So, the file would look something like:


<%@ ServiceHost Language="C#" Debug="true" Service="WcfService.GeneralService" 
CodeBehind="GeneralService.svc.cs" 
Factory="Ninject.Extensions.Wcf.NinjectServiceHostFactory" %>


Then you can inject dependencies into the service as needed as follows:


[Inject]
public IUsersRepository _repository { private get; set; }

Now we're assuming that you're using a WCF application project - so, to initialise Ninject correctly you need to make changes to the WCF project Global.asax file as follows:


  1. Make Global extend NinjectWcfApplication   (from Ninject.Extensions.Wcf)
  2. Implement and override CreateKernel - so the file looks like this:

    public class Global : NinjectWcfApplication

    {
    // Other methods omitted for clarity...
 
        protected override Ninject.IKernel CreateKernel()
        {
            IKernel k =  new StandardKernel(new ServiceModule());
            return k;
        }
    }


Now the ServiceModule is a Ninject module that would look something like:


    public class ServiceModule : NinjectModule
    {
        public override void Load()
        {
            Bind().To();
        }
    }


Notice that we're binding the IUsersRepository to the UsersRepository implementation.

Doing this will enable Ninject to do its magic in the WCF service above where it is injected.

When Service is invoked, the Ninject factory will instantiate the class and so be able to use the module bindings to pull in the correct interface implementations.

Notice that you don't need to change service bindings, etc. 

No comments:

Post a Comment