How to chain NInject modules together
Asked Answered
S

2

11

I have a multitier application using NInject to resolve dependency injection. Each tier has a particular NInject module:

Service Layer - ServiceModule
DataLayer - DataModule

In my presentation layer I really dont want to load every single module. Instead of that I want, for an example, load the ServiceModule and the module is responsible to load its dependencies.

How can I achieve that?

For example here is my ServiceModule:

public class ServicesModule : NinjectModule
{
    public override void Load()
    {
        ...
        Bind<IProductService>().To<ProductService>();
        ...
    }
}
Seam answered 25/1, 2013 at 16:6 Comment(0)
C
18

Simple, inside a NInject module you can access the kernel:

Kernel.Load(new [] { new [YourModule]() });
Cerebrum answered 25/1, 2013 at 16:7 Comment(2)
If you bring in the Ninject namespace by adding using Ninject; you will also get an extension method that provides a Kernel.Load method that makes it even easier... Kernel.Load(params INinjectModule[] modules);.Vogue
Is there a non-custom way to avoid multiple module initialization when there are shared modules present in the module hierarchy? Suppose I have module A that depends on module C and module B that depends on module C. If I call Kernel.Load(C) in both A and B, Ninject will yell at me saying that module C is already initialized.Tempting
E
-2

If your module has a single module it depends on, you can inherit from that module (instead of NinjectModule) and call base.Load():

public override void Load()
{
    base.Load();
    ...
}

This will effectively chain the modules.

Ephemeron answered 18/1, 2016 at 13:35 Comment(1)
Allthough im not yet that familiar with Ninject, inheriting in general always implies an is Relation. What the OP wants is an association from ServiceModule to DataModuleNipa

© 2022 - 2024 — McMap. All rights reserved.