这MSDN Blog Post建议使用工厂模式来获取“每个应用程序请求的 UserManager 实例”。同时,我的 Web 应用程序抛出一个错误,指出“如果多个线程同时访问同一个上下文实例”是有问题的。该博客似乎与异常消息相矛盾。给了什么?
我收到的异常发生在以下调用中:
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
更大的博客上下文:
You can use Factory implementation to get an instance of UserManager from the OWIN context. This pattern is similar to what we use for getting AuthenticationManager from OWIN context for SignIn and SignOut. This is a recommended way of getting an instance of UserManager per request for the application.
完整的异常文本:
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. "
请您参考如下方法:
FactoryPattern 不会破坏 DbContext;相反,它可以防止多线程问题。
UserManager.CreateAsync 抛出了异常,因为我们没有正确实现工厂模式。
以下是正确的。它为每次调用 UserManagerFactory 函数创建一个新的 MyDbContext 实例,并防止多线程问题。
UserManagerFactory
= () => new UserManager<IdentityUser>(new UserStore<IdentityUser>(new MyDbContext()));
以下是不正确的。它看起来与上面类似,但它不会为每次调用 UserManagerFactory 创建一个新实例。这就是我们正在使用的,因此我们有一个 DbContext 用于应用程序,这意味着同时与多个线程共享它,以及 blammo,异常。
var userStore = new UserStore<IdentityUser>(new MyDbContext());
var userManager = new UserManager<IdentityUser>(userStore);
UserManagerFactory = () => userManager;
