Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Why is this happening when we make a call to the AccountApiController.Register() method?

  • what is trying to use the context?
  • what is trying to create the context?
  • how do we avoid this?
  • how do we debug this?

"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.",

"ExceptionType":"System.InvalidOperationException",

"StackTrace":"

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()"

like image 852
Shaun Luttin Avatar asked Jan 24 '14 23:01

Shaun Luttin


2 Answers

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; 
like image 196
Shaun Luttin Avatar answered Sep 21 '22 07:09

Shaun Luttin


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

like image 33
Rafal Cypcer Avatar answered Sep 20 '22 07:09

Rafal Cypcer