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?
2 Answers
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);
}

- 158,293
- 28
- 286
- 335
-
1Does Microsoft have a way to inject Ninject modules (or the kernel) higher up so you don't have to do any service locating? (not a big deal for just a couple of dependency - just curious) – DanCaveman Sep 22 '12 at 06:02
-
Nope. Not that you are starting up much like a console app. You could make take an abstract factory (or factory method) pattern approach to creating your service, if you need to do so. – Christopher Stevenson Dec 23 '12 at 21:07
-
Dan, the Main method is the starting point. The solutions for web applications etc. are actually workarounds because a web application doesn't have a good starting point. – Niels Brinch Aug 27 '13 at 20:18
-
1Why not `ServicesToRun = new ServiceBase[] { kernel.Get
() };`? In case the service's constructor arguments change... – user1713059 Dec 08 '16 at 16:25 -
I actually have a situation when on production the creation of `barDependency` takes over 30s and the service does not start at all (not responded in a timely fashion). This makes me wonder if creating the service this way is a good idea (or is my case an isolated example of rogue Ninject bindinsgs/EF problems/...) – user1713059 Dec 08 '16 at 16:56
Using Ninject with TopShelf.. run vs install(start)
I faced a strange issue where > MyService.exe run
works fine with the code Kernel.Bind(handlers => { var bindings = handlers.From("abc.dll") ... }
But when i start the service after installing using > MyService.exe install
it could not resolve the bindings mentioned in Ninject assembly scanning.
After a few hours of breaking my head...
changing the .From(...)
to .FromAssembliesMatching(...)
i could start the service successfully.
Hope it helps someone.