4

What is the difference between these two methods to create UserManager?

var userManager1 = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var userManager2 = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(dbContext));

The IdentitySamples application uses HttpContext.GetOwinContext for both UserManager and RoleManager. Also AccountController in default MVC 5 application template uses HttpContext.GetOwinContext but when I create a new controller which uses UserManager. It uses db (the ApplicationDbContext)

Default AccountController

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

//can be used as
public ActionResult Index()
{
    return View(UserManager.Users.ToList());
}

Any new controller

private ApplicationDbContext db = new ApplicationDbContext();

//can be used as
public ActionResult Index()
{
    return View(db.Users.ToList());
}

Which of the two methods should be used in which case?

SMUsamaShah
  • 7,677
  • 22
  • 88
  • 131
  • IMO, you should not use either of these methods. Instead, set up the `UserManager` as a dependency in an Inversion of Control container, and then constructor inject it where it is needed. Other than that, the `UserManager` gives you more behavior than a plain `DbContext`, such as password hashing and email confirmation features. – danludwig Mar 16 '15 at 12:40

0 Answers0