Get an instance of an object with Ninject
Asked Answered
C

1

21

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!!
}
Coachandfour answered 10/10, 2011 at 20:8 Comment(0)
F
35

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?

Fraley answered 10/10, 2011 at 20:23 Comment(7)
No no, I understood it. What I want is to retrieve an instance of an object. I arrived at this point: new StandardKernel().Get<IRepository>(); Is this correct?Coachandfour
Well, you should probably put IRepository in the constructor for your controller. But I wouldn't create a new StandardKernel as one is already constructed for you and available at System.Web...CurrentFraley
I understand .. this is what I want, but the code was bitten .. System.Web ..... Current? How do I recover the current kernel Ninject?Coachandfour
I cut it off because it was the code in my answer. System.Web.Mvc.DependencyResolver.Current gives you the current Ninject kernel. Then you call GetService for the specific type you want to resolve.Fraley
Thank you. You helped me a lot! In fact, my repository is passed by constructor, what need is an instance of a IEmailSender (otherwise, my test will always send emails). This code is simplified. I decided to not put it in the constructor because this object will only be used in a single actionCoachandfour
I would like to point out that for me, the call to DependencyResolver.Current.GetService to retrieve an instance of my ICoolService did not respect the InRequestScope of the binding. This was within an ASP.NET MVC application, so be careful about that.Too
Or more succinctly, you can do DependencyResolver.Current.GetService<ICoolObject>();Wandy

© 2022 - 2024 — McMap. All rights reserved.