模板AccountController中的UserManager帮助方法

时间:2014-05-28 02:31:11

标签: asp.net-mvc asp.net-identity owin asp.net-identity-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对象的构造函数?

1 个答案:

答案 0 :(得分:2)

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

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

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

相关问题