سؤال

I setup my DbContext modeled after a post here on stackoverflow found here.

This is the current setup...

public static class DbContext
{
    public static MyDbContext Db
    {
        get
        {
            if (!HttpContext.Current.Items.Contains("_db"))
            {
                HttpContext.Current.Items.Add("_db", new MyDbContext());
            }
            return HttpContext.Current.Items["_db"] as MyDbContext;
        }
    }
}

The context is disposed in global.asax on end_request like so:

    void Application_EndRequest(object sender, EventArgs e)
    {
        var db = (MyDbContext)HttpContext.Current.Items["_db"];
        if (db != null)
            db.Dispose();
    }

That way, throughout my system I can access the Db like DbContext.Db.xxxx

So far, everything is running great for me locally, however, I haven't tested with multiple users in a production environment.

My Concern...

I read this post on stackoverflow and now it has me worried that there could be data issues with multiple users accessing the static context. Should this concern me or is the way I have it setup ok?

هل كانت مفيدة؟

المحلول

The setup IS ok...

My solution doesn't use a static DbContext. The DbContext (or whatever is needed) is stored in the HttpContext.Current.Items collection (that is a current HTTP request specific) and the property is equivalent to a method call that would retrieve the context from this collection and instantiate it if needed. This collection was chosen for its safety and for the fact it's easy to reference it pretty much from anywhere (namely from the Application_EndRequest event) so we can dispose it when we're done.

There's a big difference to the post you've linked, because it describes a situation where you use a static field. That field would obviously be shared between all users and that would be a big problem.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top