C#, Ninject: Where do you put the kernel and your modules?

别来无恙 提交于 2019-12-03 06:37:17

You may create static wrapper class for kernel. That way you could do something like ServiceLocator.Resolve()

For registering services there are two ways: inline and module registration. Both of them should be loaded at bootstrapping. Module is better for organizing.

Maybe it would be easier to start with StructureMap because there is static class and it has auto mapping features.

Those screencasts should get you starting:

Ruben Bartelink

+1'd Marek's answer - definitely look through those resources.

Some points...

You're definitely right to try this, even in a small app. Its also important to think hard about superficially simple questions like the one you posed. For DI, you really do have to actually do some work with it to really appreciate it - I for one was in the "Oh, I've only got a small app" (denial) camp for a long time until I actually used it.

There's a school of though that one in general should be steering away from Service Locator and just having injection [without any dependencies on a container].

If you dont use Service Locators, nobody needs to know where the Container (Kernel) is, which is the best thing.

Modules are mainly for the purposes of compartmentalising batches of things to register in a particular overall Container (Kernel).

Surely there's a canonical 'Global Container' Singleton implementation out there for Ninject? EDIT: Just found one:- http://www.codethinked.com/creating-a-binding-factory-for-ninject

See also Ninject: How do I inject into a class library?

My point of view: as Marek said, you should create some (probably static) wrapper for the Kernel, which contains the IKernel instance. It should contain the Resolve< T> method, and probably Load(INinjectModule module) method - all static.

In each assembly, you can simply define your own INinjectModule that maps classes inside this assembly.

The Kernel wrapper is in the 'lowest', the most common assembly (typically the one where Log and Utils are). It is because Kernel has to be accessible from all parts - so it must be in the assembly, which is referenced by all others. If you don't have one, you are always free enough to create one. This might seem a little tricky, one could expect that Kernel will be in the 'highest' assembly (the executable one). Not true.

To register all your modules from your assemblies, simply call Kernel.Load(new XXModule) in each of them.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!