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

后端 未结 3 1774

I\'m creating a tiny C# application, which currently consists of a core assembly and a winforms assembly. I realize I probably don\'t really need Ninject in a small thing like t

相关标签:
3条回答
  • 2021-02-08 22:14

    +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?

    0 讨论(0)
  • 2021-02-08 22:18

    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.

    0 讨论(0)
  • 2021-02-08 22:31

    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:

    • Dime Casts series for Ninject
    • Dime Casts series for StructureMap
    0 讨论(0)
提交回复
热议问题