如何将NInject模块链接在一起

9 c# asp.net dependency-injection ninject

我有一个使用NInject的多层应用程序来解决依赖注入问题.每个层都有一个特定的NInject模块:

Service Layer - ServiceModule
DataLayer - DataModule

在我的表示层中,我真的不想加载每个模块.而不是我想要的,例如,加载ServiceModule并且模块负责加载其依赖项.

我怎样才能做到这一点?

例如,这是我的ServiceModule:

public class ServicesModule : NinjectModule
{
    public override void Load()
    {
        ...
        Bind<IProductService>().To<ProductService>();
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

gus*_*ico 16

很简单,在NInject模块中,您可以访问内核:

Kernel.Load(new [] { new [YourModule]() });
Run Code Online (Sandbox Code Playgroud)

  • 如果你通过添加`using Ninject;'来引入Ninject命名空间,你还将得到一个扩展方法,它提供了一个`Kernel.Load`方法,使它更容易......`Kernel.Load(params INinjectModule [] modules); `. (3认同)