Search code examples
c#asp.net-coreentity-framework-coredbcontextasp.net-core-identity

Safely use ASP.NET Core's UserManager and IdentityDbContext simultaneously


Whenever I do anything related to auth, I use UserManager rather than IdentityDbContext. I always avoided using both simultaneously as I'm unsure how they interact.

Now I find myself in a situation that I need to query the database, so must use the context.

I register my context as per request, I think UserManager is also registered that way when calling services.AddIdentityCore() in startup.

What I'm worried about: if I perform work in one then is it safe to use from the other, will there be implicit race conditions based on which calls "save" first, do they share a change tracker, etc.?

Is it "safe" to use both at the same time?


Solution

  • I use both in an override of UserClaimsPrincipalFactory, without problems. I call UserManager.UpdateAsync() to save updates to the user, and use the injected context to retrieve additional data related to user authorizations.