构造函数依赖注入在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?

如果你想拥有你必须定义一个定制的控制器工厂参数构造函数。菲尔哈克有很大的博客帖子这个话题。

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.

如果您不希望推出自己的控制器工厂,你可以让他们pre-作出的的 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.