“Context cannot be used while the model is being created” exception with ASP.NET Identity

The problem was that we were NOT using the factory pattern that MS recommends.

You can use Factory implementation to get an instance of UserManager
from the OWIN context. … This is a recommended way of getting an instance of
UserManager per request for the application.

As a result, “the same context instance is accessed by multiple threads concurrently,” because several requests and thus threads shared a DbContext.

This following is correct. It creates a new instance of MyDbContext for each call to the UserManagerFactory function.

UserManagerFactory 
= () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()));

The following is incorrect. It look similar but does not create a new instance for each call to UserManagerFactory. It is what we were using, ergo our site broke.

var userStore = new UserStore<IdentityUser>(new MyDbContext());                    
var userManager = new UserManager<IdentityUser>(userStore);
UserManagerFactory = () => userManager;

Leave a Comment