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

"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;


This error can also occur in case of incorrect connectionString. Check if connectionString is valid (no typo etc.).


Do you override the OnModelCreating method? If so, can you share it or the whole context class?

If not, you should pay attention to the following in the error message

or if the same context instance is accessed by multiple threads concurrently. Note that instance members of DbContext and related classes are not guaranteed to be thread safe.

If that doesn't help, do you use an unchanged Web API project which is created by Visual Studio?