2

模板 AccountController 类(VS 2013 Update 2)包括以下代码:

public class AccountController : Controller
{
    private ApplicationUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(ApplicationUserManager userManager)
    {
        UserManager = userManager;
    }

    public ApplicationUserManager UserManager {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

所以这里我们有一个漂亮的ApplicationUserManager辅助属性,它返回一个保存的 ApplicationUserManager 对象(如果调用了第二个构造函数),或者如果调用了无参数构造函数,则返回从 Owin 管道获取的 ApplicationUserManager。

问题:有什么东西会调用传入 ApplicationUserManager 对象的构造函数吗?

4

1 回答 1

2

默认情况下不是。但是,如果您开始使用 DI 框架,您可以设置 DI 框架以向您的控制器注入任何构造函数,在您的情况下为ApplicationUserManager

默认情况下,MVC 控制器需要空构造函数才能工作,但如果您使用 DI 框架,则可以将其配置为注入任何类型的构造函数。使用构造函数注入的优点是可以模拟每个依赖对象。

如果您想使用任何 DI 框架,我应该推荐 AutoFac,https://code.google.com/p/autofac/wiki/MvcIntegration

于 2014-05-28T07:58:52.210 回答