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!!
}
ridermansb
  • 10,779
  • 24
  • 115
  • 226

1 Answers1

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?

Buildstarted
  • 26,529
  • 10
  • 84
  • 95
  • No no, I understood it. What I want is to retrieve an instance of an object. I arrived at this point: `new StandardKernel().Get();` **Is this correct?** – ridermansb Oct 10 '11 at 20:34
  • 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...Current` – Buildstarted Oct 10 '11 at 20:38
  • I understand .. this is what I want, but the code was bitten .. System.Web ..... Current? How do I recover the current kernel Ninject? – ridermansb Oct 10 '11 at 20:51
  • 2
    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. – Buildstarted Oct 10 '11 at 21:11
  • 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 action – ridermansb Oct 10 '11 at 21:22
  • 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. – Umar Farooq Khawaja Aug 30 '12 at 16:19
  • 1
    Or more succinctly, you can do `DependencyResolver.Current.GetService();` – GONeale Jan 16 '15 at 02:39