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

后端 未结 7 1254
遥遥无期
遥遥无期 2020-12-01 07:42

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
7条回答
  •  执笔经年
    2020-12-01 07:44

    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(new UserStore(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(new MyDbContext());                    
    var userManager = new UserManager(userStore);
    UserManagerFactory = () => userManager;
    

提交回复
热议问题