Get an instance of an object with Ninject

前端 未结 1 1957
余生分开走
余生分开走 2021-02-07 03:00

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 depend

1条回答
  •  孤城傲影
    2021-02-07 03:17

    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().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 讨论(0)
提交回复
热议问题