Ninject 模块的意图是什么?

编程入门 行业动态 更新时间:2024-10-25 01:28:37
本文介绍了Ninject 模块的意图是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是一个完全的新手

我一直在拆解别人的代码,发现了几个 nInject 模块的实例 - 派生自 Ninject.Modules.Module 的类,并且有一个包含大部分代码的 load 方法.

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.

你们其余的问题听起来更多的是关于 IoC 和 DI 的整体,而不仅仅是 Ninject.是的,您可以使用静态 Configuration 对象来完成 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 模块的意图是什么?

本文发布于:2023-05-27 09:57:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285764.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:意图   模块   Ninject

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!