简体   繁体   中英

Is this a bad way of using DbContext for EF CodeFirst?

I have one base controller class which has following DbContext. Instead of using "using" statement for each database work, can I rely on this. So far app runs as expected. I am not sure if Dispose part is really needed.

private static Context _database;

public static Context Db
{
    get 
    { 
        if (_database == null)
        {
            _database = new Context();
        }
        return _database;
    }
}

protected override void Dispose(bool disposing)
{
    if (_database == null)
    { 
        _database.Dispose(); 
    }

    base.Dispose(disposing);
}

No. not sure what class is being disposed of here but if it ever got disposed it would crash every time after that. you have to set _database = null after calling dispose or you would use it in a disposed state. if you want to do any type of multi threading this won't work. if more than 1 user is using this at same time it will crash. you won't be able to unit test the use of database with static either. It will cache all data you get causing stale data after a time too unless you are only user.

Having a automatic disposal of requests is very convenient don't make it a manual task.

Just don't use static in anyway, always using using statement for every request.

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