Are controller factories neccessary when using Ninject in ASP.NET mvc 4

二次信任 提交于 2019-12-07 00:00:44

问题


I am at a loss of what to do with the multitude of documentation available through google in .net as regards using Ninject with asp.net mvc 4

First of all, i want to know if Controller factories are neccessary in asp.net.

Also, is constructor injection really the only way we can do dependency injection with MVC 4 because property injection and method injection does not seem to work when i use them with my controllers


回答1:


I am not an expert on Ninject but as far as i know, i am only using it to link my DataSource Interface and my EfDb Class to the rest of my application.

If you need a good book that has a Real Application built around Ninject try: Pro ASP.NET MVC 3 Framework, Third Edition

or

Pro Asp.Net Mvc 4

There are very few lines of code i am usually concerned with

public class NinjectControllerFactory : DefaultControllerFactory
{
    private IKernel ninjectKernel;

    public NinjectControllerFactory()
    {
        ninjectKernel = new StandardKernel();
        AddBindings();
    }

    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        return controllerType == null
                   ? null
                   : (IController) ninjectKernel.Get(controllerType);
    }

    private void AddBindings()
    {
        ninjectKernel.Bind<IDataSource>().To<EfDb>();
    }
}

Then register your NinjectControllerFactory in Global.asax.cs with:

ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

As you can see, this class use Method Injection using private void AddBindings(). This makes it very easy if you are following Test Driven Development (TDD)




回答2:


See the documentation here: https://github.com/ninject/ninject.web.mvc/wiki/Dependency-injection-for-controllers, "The only thing that has to be done is to configure the Ninject bindings for its dependencies. The controller itself will be found by Ninject even without adding a binding."

NInject will automagically set up your controller dependencies (provided it has a binding for those types).



来源:https://stackoverflow.com/questions/15333923/are-controller-factories-neccessary-when-using-ninject-in-asp-net-mvc-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!