[英]Do I need to call context.dispose when adding the dbcontext with DI?
[英]Do I need to Dispose DbContext when using an InMemoryDatabase?
在我的单元测试中,我将 EF Core 2.2 与InMemoryDatabase一起使用,例如:
var dbOptions = new DbContextOptionsBuilder<MyContext>().UseInMemoryDatabase("Foo").Options;
using (var context = new MyContext(dbOptions));
{
// Do stuff..
}
使用UseInMemoryDatabase
,我真的需要处理DbContext
吗? 阅读Jon Gallants 博客后,我意识到即使使用真正的 SQL 数据库提供程序,也不总是需要Dispose()
。 使用 InMemoryDatabase 时处理DbContext
有什么意义? 我可以把它留给GC吗?
只要上下文没有依赖关系,比如应该在处置时释放的数据库连接或文件资源,你就可以省略处置。
所有超出范围的引用都会自动标记为垃圾收集。
从代码的外观来看,您有一个using
块,在我看来这是一件好事,因为一旦运行代码离开您的using
块,就会调用Dispose
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.