在ASP.NET MVC 4中使用Ninject时是否需要控制器工厂 [英] Are controller factories neccessary when using Ninject in ASP.NET mvc 4

查看:58
本文介绍了在ASP.NET MVC 4中使用Ninject时是否需要控制器工厂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于将Ninject与asp.net mvc 4结合使用,我不知道该如何处理通过.net谷歌提供的大量文档

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

首先,我想知道asp.net中控制器工厂是否必要.

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

此外,构造函数注入确实是我们可以使用MVC 4进行依赖注入的唯一方法,因为当我将它们与控制器一起使用时,属性注入和方法注入似乎不起作用

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

推荐答案

我不是Ninject的专家,但据我所知,我仅使用它将我的DataSource InterfaceEfDb Class链接到我的应用程序的其余部分.

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.

如果您需要一本不错的书,该书具有围绕Ninject构建的Real Application,请尝试:

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

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>();
    }
}

然后在Global.asax.cs中通过以下方式注册您的NinjectControllerFactory:

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

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

如您所见,该类使用Method Injectionprivate void AddBindings().如果您遵循Test Driven Development (TDD)

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)

这篇关于在ASP.NET MVC 4中使用Ninject时是否需要控制器工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆