开发者

Get an instance of an object with Ninject

I installed on my project Ninject.MVC3 via Nuget.

I read this article that to inject dependencies in my controll开发者_如何学JAVAers, 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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜