简体   繁体   中英

How to make calls to DbContext Threadsafe

I'm using EF6 and currently I occasionally get an error;

Action Unhandled Exception: 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.

I have read through a couple of useful answer on the topic here and here and I understand the basic concept of what is going wrong, but I'm unsure about how exactly to make a change that will resolve this issue.

I use a Base Controller class that all other Controllers inherit from which I've included the relevant code for below. I use two Contexts, one for my application data; DataModel , and one for the ASP NET Identity 2.0 tables; ApplicationDbContext . I thought that each new request would instantiate a new Base Controller and therefore new Contexts?

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"));
    }
}

Any advice or examples on what changes I need to make would be much appreciated.

Custom attributes / filters can cause concurrency issues. Do you have any in your derived controllers?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM