Accessing UserManager outside AccountController

If you’re using the default project template, the UserManager gets created the following way:

In the Startup.Auth.cs file, there’s a line like this:

app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

that makes OWIN pipeline instantiate an instance of ApplicationUserManager each time a request arrives at the server. You can get that instance from OWIN pipeline using the following code inside a controller:

Request.GetOwinContext().GetUserManager<ApplicationUserManager>()

If you look carefully at your AccountController class, you’ll see the following pieces of code that makes access to the ApplicationUserManager possible:

    private ApplicationUserManager _userManager;

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

Please note, that in case you need to instantiate the ApplicationUserManager class, you need to use the ApplicationUserManager.Create static method so that you have the appropriate settings and configuration applied to it.

Leave a Comment