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

查看:274
本文介绍了构造函数依赖注入在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.

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

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