Using Ninject with a Windows Service

BuddyJoe picture BuddyJoe · Apr 23, 2012 · Viewed 8.2k times · Source

Any good examples of using Ninject with a Windows Service? I'm not sure what if any extensions I need. Also, not sure what the Composition Root should be? Any good examples of using Ninject with a Windows service out there?

Answer

BrokenGlass picture BrokenGlass · Apr 23, 2012

A windows service does not differ much from a regular command line application in regard to dependency injection. The straight-forward composition root is your Main method.

The way I usually have done it is create the StandardKernel there with a module in which my dependencies are resolved. Then use kernel.Get to resolve the top level dependencies - everything else will follow from there:

static void Main(string[] args)
{
    var kernel = new StandardKernel(new FooModule());
    var barDependency = kernel.Get<Bar>();

    System.ServiceProcess.ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] { new FooService(barDependency) };
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}