【发布时间】:2015-07-28 09:41:53
【问题描述】:
我正在使用 EF6,目前偶尔会出错;
动作未处理异常:创建模型时无法使用上下文。如果在 OnModelCreating 方法中使用上下文,或者多个线程同时访问同一个上下文实例,则可能会引发此异常。请注意,不保证 DbContext 和相关类的实例成员是线程安全的。
我已经阅读了有关 here 和 here 主题的几个有用答案,并且我了解出了什么问题的基本概念,但我不确定如何进行更改才能解决此问题问题。
我使用所有其他控制器继承的基本控制器类,我在下面包含了相关代码。我使用两个上下文,一个用于我的应用程序数据; DataModel,一个用于 ASP NET Identity 2.0 表; ApplicationDbContext。我认为每个新请求都会实例化一个新的基本控制器,从而实例化新的上下文?
public class BaseController : Controller
{
protected DataModel db = new DataModel();
/// <summary>
/// Application DB context
/// </summary>
protected ApplicationDbContext ApplicationDbContext { get; set; }
/// <summary>
/// User manager - attached to application DB context
/// </summary>
protected UserManager<ApplicationUser> UserManager { get; set; }
public BaseController()
{
this.ApplicationDbContext = new ApplicationDbContext();
this.UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.ApplicationDbContext));
// We need to allow the user name to also be the email address
UserManager.UserValidator = new UserValidator<ApplicationUser>(UserManager) { AllowOnlyAlphanumericUserNames = false };
// Setup a token for Password Resets
var provider = Startup.DataProtectionProvider;
UserManager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(provider.Create("UserToken"));
}
}
任何关于我需要进行哪些更改的建议或示例将不胜感激。
【问题讨论】:
-
一般情况下,我们在多线程场景中使用
lock。 -
我认为您的问题在于
UserStore上下文的创建,请参阅以下stackoverflow.com/questions/21344232/… -
您可以为您的上下文使用
Lazy<T>初始化,然后再次使用相同的上下文。
标签: c# multithreading entity-framework