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

查看:43
本文介绍了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天全站免登陆