什么是Ninject模块的用意何在? [英] What is the intention of Ninject modules?

查看:205
本文介绍了什么是Ninject模块的用意何在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个完整的新手到nInject

I'm a complete newbie to nInject

我已经拉开别人的代码,发现的nInject模块的多个实例 - 从Ninject.Modules派生的类.Module,并有一个包含大部分的代码加载方法。

I've been pulling apart someone else's code and found several instances of nInject modules - classes that derive from Ninject.Modules.Module, and have a load method that contains most of their code.

这些类是通过调用StandardKernel的实例中的LoadModule方法,并传递给它的一个实例调用模块类。

These classes are called by invoking the LoadModule method of an instance of StandardKernel and passing it an instance of the module class.

也许我缺少明显的东西在这里,但这个又是什么在刚刚创建一个普通的老类和调用它的方法,或者是一个利益用一个静态方法静态类?

Maybe I'm missing something obvious here, but what is the benefit of this over just creating a plain old class and calling its method, or perhaps a static class with a static method?

推荐答案

的Ninject模块是用来与IoC容器注册各种类型的工具。的优点是,这些模块然后保持在自己的类。这允许你把不同的层/服务在自己的模块。

The Ninject modules are the tools used to register the various types with the IoC container. The advantage is that these modules are then kept in their own classes. This allows you to put different tiers/services in their own modules.

// some method early in your app's life cycle
public Kernel BuildKernel()
{
    var modules = new INinjectModule[] 
    {
        new LinqToSqlDataContextModule(), // just my L2S binding
        new WebModule(),
        new EventRegistrationModule()
    };
    return new StandardKernel(modules);
}

// in LinqToSqlDataContextModule.cs
public class LinqToSqlDataContextModule : NinjectModule
{
    public override void Load()
    {
        Bind<IRepository>().To<LinqToSqlRepository>();
    }
}



拥有多个模块,使得关注点分离,即使在你的IoC容器。

Having multiple modules allows for separation of concerns, even within your IoC container.

你质疑其余听起来像它更多的是国际奥委会和DI作为一个整体,而不仅仅是Ninject。是的,你可以使用静态配置对象做只是,一个IoC容器做的一切。 IoC容器中,成为非常好的,当你有依赖关系的多个层次。

The rest of you question sounds like it is more about IoC and DI as a whole, and not just Ninject. Yes, you could use static Configuration objects to do just about everything that an IoC container does. IoC containers become really nice when you have multiple hierarchies of dependencies.

public interface IInterfaceA {}
public interface IInterfaceB {}
public interface IInterfaceC {}

public class ClassA : IInterfaceA {}

public class ClassB : IInterfaceB
{
    public ClassB(IInterfaceA a){}
}

public class ClassC : IInterfaceC
{
    public ClassC(IInterfaceB b){}
}

建筑ClassC是一种痛苦在这一点上,与接口多个深度。 。这是很容易,只是要求一个IInterfaceC内核

Building ClassC is a pain at this point, with multiple depths of interfaces. It's much easier to just ask the kernel for an IInterfaceC.

var newc = ApplicationScope.Kernel.Get<IInterfaceC>();

这篇关于什么是Ninject模块的用意何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆