Using Ninject with a Windows Service

2020-06-07 07:11发布

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条回答
2楼-- · 2020-06-07 07:33

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);
}
查看更多
爷的心禁止访问
3楼-- · 2020-06-07 07:36

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.

查看更多
登录 后发表回答