得到与Ninject一个对象的一个​​实例 [英] Get an instance of an object with Ninject

查看:120
本文介绍了得到与Ninject一个对象的一个​​实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我安装在我的项目 Ninject.MVC3 通过的NuGet。

我看了这篇文章,要注入依赖在我的控制器,你所要做的就是安装Ninject,加入NinjectMVC3.cs并准备好我的依赖关系。

到目前为止好,但如何检索对象的实例?

 公众的ActionResult MyAction()
{
    VAR myObject的= / *这里?* /
}

在控制器的构造函数中的我没有问题!

 公共类的AccountController:控制器
{
    公众的AccountController(IRepository库){...} //这个作品!
}


解决方案

它的工作原理的原因是因为的Con​​trollerFactory查找DI,并自动添加它。如果你想获得一个特定的实例,你可以这样做:

 私有静态无效RegisterServices(内核的iKernel){
    kernel.Bind< ICoolObject>()来(CoolObject)。
}公众的ActionResult MyAction(){
    VAR myObject的=
        System.Web.Mvc.DependencyResolver.Current.GetService(typeof运算(ICoolObject));
}

Becareful虽然。这与那些新的依赖注入做得相当频繁(包括我自己)。问题是,为什么你需要做这种方式?

I installed on my project Ninject.MVC3 via Nuget.

I read this article that to inject dependencies in my controllers, all you had to do was install Ninject, add my dependencies in NinjectMVC3.cs and ready.

So far so good, but how to retrieve the instance of an object?

public ActionResult MyAction()
{
    var myObject = /* HERE  ??*/
}

In the constructor of the controller I have no problems!

public class AccountController : Controller
{
    public AccountController(IRepository repository) { ... } //This works!!
}

解决方案

The reason it works is because the ControllerFactory looks for DI and automatically adds it. If you want to get a specific instance you can do this:

private static void RegisterServices(IKernel kernel) {
    kernel.Bind<ICoolObject>().To(CoolObject);
}

public ActionResult MyAction() {
    var myObject = 
        System.Web.Mvc.DependencyResolver.Current.GetService(typeof (ICoolObject));
}

Becareful though. This is done quite often with those new to Dependency Injection (myself included). The question is why do you need to do it this way?

这篇关于得到与Ninject一个对象的一个​​实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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