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

asp.net asp.net-identity c# entity-framework multithreading


Why does this occur when the AccountApiController.Register() method is called?

  • What aims to utilize the context?
  • What tries to establish the context?
  • How can we prevent this?
  • How can this be debugged?

"Message":"An error has occurred.",

"ExceptionMessage":"The context cannot be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method 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.",



at System.Web.Http.ApiController.d__1.MoveNext()

--- End of stack trace from previous location where exception was thrown

at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

at System.Runtime.CompilerServices.TaskAwaiter .HandleNonSuccessAndDebuggerNotification(Task > task)

at System.Web.Http.Dispatcher.HttpControllerDispatcher.d__0.MoveNext()"

10/7/2016 2:46:30 PM

Accepted Answer

We had a difficulty since we weren't following the factory pattern, which was MS suggests.

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, several requests and therefore threads shared a DbContext, causing "the same context instance to be used by numerous threads concurrently."

The next sentence is accurate. For each call to the UserManagerFactory method, a fresh instance of MyDbContext is created.

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

The next statement is inaccurate. Although it has a similar appearance, it does not produce a new instance with each call to the UserManagerFactory. Because we were utilizing it, our website crashed.

var userStore = new UserStore<IdentityUser>(new MyDbContext());                    
var userManager = new UserManager<IdentityUser>(userStore);
UserManagerFactory = () => userManager;
1/25/2014 3:08:36 AM

Popular Answer

This issue can also happen when there areconnectionString . Verify ifconnectionString is true (no typo etc.).

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow