Identity: How to use UserManager in Startup.cs class

Created on 29 Dec 2016  路  9Comments  路  Source: aspnet/Identity

Help me please

In Startup.Auth.cs:
private void ConfigureAuth(IApplicationBuilder app)
{
username = "test";
_userManager = app.ApplicationServices.GetRequiredService();
_userManager = app.ApplicationServices.GetRequiredService();
var user = _userManager.FindByNameAsync(username).Result;
}

always responds with the cached data ((

related
I need to use in Token Provider:
https://github.com/nbarbettini/SimpleTokenProvider/issues/11#issuecomment-269484942

Most helpful comment

@Vaylandt
It's cached (or will be treated as a singleton) because there is only one scope at that point. You need to create and dispose a new scope this way:

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
    var signInManager = serviceScope.ServiceProvider.GetService<SignInManager<User>>();
    var userManager = serviceScope.ServiceProvider.GetService<UserManager<User>>();
}

All 9 comments

UserManagers need to be scoped as the stores depend on DbContext's which need to be scoped as well. Capturing a user manager for reuse inside of startup is not a good idea.

@HaoK ,It's clear :)
And what solution do you suggest?
I need a token provider and check through Identity simultaneously.

What are you trying to do exactly?

@Vaylandt
It's cached (or will be treated as a singleton) because there is only one scope at that point. You need to create and dispose a new scope this way:

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
    var signInManager = serviceScope.ServiceProvider.GetService<SignInManager<User>>();
    var userManager = serviceScope.ServiceProvider.GetService<UserManager<User>>();
}

@VahidN , thank you very much!!! RESOLVED!

@VahidN , one question, how fast this work?
Wouldn't it be reasonable to move JWT Provider in a regular controller?

A regular controller does this scope creation and disposing behind the scene. It's part of a request life cycle. That's why you won't see that cached behavior at there.

@VahidN , thank You for the answers!

Thanks! Worked for me

Was this page helpful?
0 / 5 - 0 ratings

Related issues

danroth27 picture danroth27  路  4Comments

anester picture anester  路  9Comments

andrew-vdb picture andrew-vdb  路  9Comments

suhasj picture suhasj  路  7Comments

trailmax picture trailmax  路  6Comments