Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ninject with a Windows Service

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?

like image 883
BuddyJoe Avatar asked Apr 23 '12 18:04

BuddyJoe


People also ask

Why Ninject is used?

Ninject is a lightweight dependency injection framework for . NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner.

What is a ninject module?

The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.

Is ninject open source?

Ninject is and will always be free for both personal and commercial projects. It's also open source, so you can fork the code and make any changes you like.

What is dependency injection C# with example?

Using dependency injection, we can pass an instance of class C to class B, and pass an instance of B to class A, instead of having these classes to construct the instances of B and C. In the example, below, class Runner has a dependency on the class Logger.


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);
}
like image 90
BrokenGlass Avatar answered Sep 25 '22 19:09

BrokenGlass


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.

like image 25
CGSK Avatar answered Sep 25 '22 19:09

CGSK