ASP.NET MVC控制器中的构造函数依赖注入

ASP.NET MVC控制器中的构造函数依赖注入

问题描述:

考虑:

public class HomeController : Controller 
{
    private IDependency dependency;

    public HomeController(IDependency dependency) 
    {
        this.dependency = dependency;
    }
}

而ASP.NET MVC中的控制器必须有一个空的默认构造函数是除了定义一个空(并且在我看来没有用)DI的构造函数之外的任何方式。

And the fact that Controllers in ASP.NET MVC must have one empty default constructor is there any way other than defining an empty (and useless in my opinion) constructor for DI?

如果要使用无参数构造函数,则必须定义一个自定义控制器工厂。 Phil Haack有一个很好的博客文章关于这个问题。

If you want to have parameterless constructors you have to define a custom controller factory. Phil Haack has a great blog post about the subject.

如果您不想滚动自己的控制器工厂,可以在 ASP.NET MVC Contrib 项目在codeplex / github。

If you don't want to roll your own controller factory you can get them pre-made in the ASP.NET MVC Contrib project at codeplex/github.