EF Core中DbContext可以被Dispose多次

我们知道,在EF Core中DbContext用完后要记得调用Dispose方法释放资源。但是其实DbContext可以多次调用Dispose方法,虽然只有第一次Dispose会起作用,但是DbContext多次调用Dispose方法并不会报错。

我们看看下面的示例代码,可以看到我们调用了DbContext.Dispose三次,加上using代码块一共四次,但是代码并不会报错:

string connectionString = "Server=localhost;User Id=sa;Password=1qaz!QAZ;Database=Demo";
using (var dbContext = new MyDbContext(connectionString))//MyDbContext继承自Microsoft.EntityFrameworkCore.DbContext
{
    List<Language> languages = dbContext.Language.ToList();//通过DbContext从数据库中查询Language实体(表)的数据

    //多次调用DbContext.Dispose方法不会报错
    dbContext.Dispose();
    dbContext.Dispose();
    dbContext.Dispose();
}

但是记住当DbContext调用Dispose方法后,就不能再用DbContext去数据库操作数据了,除非重新new一个DbContext。

例如下面的代码:

string connectionString = "Server=localhost;User Id=sa;Password=1qaz!QAZ;Database=Demo";
using (var dbContext = new MyDbContext(connectionString))//MyDbContext继承自Microsoft.EntityFrameworkCore.DbContext
{
    List<Language> languages = dbContext.Language.ToList();//通过DbContext从数据库中查询Language实体(表)的数据

    dbContext.Dispose();//调用DbContext.Dispose方法

    List<Language> otherLanguages = dbContext.Language.ToList();//再次通过DbContext从数据库中查询Language实体(表)的数据,这次会抛出异常因为DbContext在上面已经被Dispose了
}

第二次调用dbContext.Language.ToList()去数据库查询数据给otherLanguages赋值的时候,会抛出异常,因为之前已经调用了DbContext.Dispose方法,DbContext已经不可用了,异常信息如下:

System.ObjectDisposedException: 'Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.'
原文地址:https://www.cnblogs.com/OpenCoder/p/10320070.html