ASP.NET MVC控制器中的构造函数依赖注入 [英] Constructor Dependency Injection in a ASP.NET MVC Controller

查看:230
本文介绍了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.

这篇关于ASP.NET MVC控制器中的构造函数依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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