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

103,286

Solution 1

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;

Solution 2

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

Solution 3

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?

Solution 4

TL&DR: If the goal is model seeding, and you are using the entity framework, i strongly suggest you take a look at the following link: https://docs.microsoft.com/en-us/ef/core/modeling/data-seeding

This link details how to directly SEED your data, during the migration itself. This is typically useful when you want to seed your data during the creation of the DATABASE instead of the start of your application.

Share:
103,286

Related videos on Youtube

Shaun Luttin
Author by

Shaun Luttin

My professional work focuses on designing, testing, implementing/securing, and deploying distributed services. I kind be "that guy" too. Ship it!

Updated on December 15, 2021

Comments

  • Shaun Luttin
    Shaun Luttin over 2 years

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

    • Daniil Grankin
      Daniil Grankin over 10 years
      Make sure that you don't use the same context object for different requests and make sure that you send request after OnModelCreating. you can add there breakpoint in end of method.
    • Shaun Luttin
      Shaun Luttin over 10 years
      How do we make sure that we don't use the same context object for different requests? Also, I am not sure what you mean by adding a breakpoint because we don't have an OnModelCreating method.
    • Shaun Luttin
      Shaun Luttin over 10 years
      I've learned that the ASP.NET Identity uses the Factory Pattern in order to get one instance of UserManager per request; this might be a problem, because our UserManager stores data in our DbContext. Hmm.
    • user2982369
      user2982369 over 7 years
      try to make your methods Async, this might solve the problem
  • Shaun Luttin
    Shaun Luttin over 10 years
    We do not override the OnModelCreating method.Also, we do not use an unchanged Web API project... rather, we have modified the DbContext which stores both ASP.NET Identity data and other website data.
  • Shaun Luttin
    Shaun Luttin over 10 years
    We aren't sure how to determine whether the same context instance is accessed by multiple threads concurrently. Hmm.
  • Reuel Ribeiro
    Reuel Ribeiro over 7 years
    Where should I put this on my project? I use Unity.Mvc as a dependency resolver. Also, I work with my own UnityOfWork which I inject a DbContext that is shared to all my repositories.
  • Austin B
    Austin B over 4 years
    I had the same error message, this fixed my problem as well. 👍🏻👍🏻@ShaunLuttin
  • Mehdi
    Mehdi about 4 years
    Same problem here and fixed by adding factory pattern. Thanks @ShaunLuttin