简体   繁体   English

使用 InMemoryDatabase 时是否需要处理 DbContext?

[英]Do I need to Dispose DbContext when using an InMemoryDatabase?

In my unit tests I use EF Core 2.2 with an InMemoryDatabase such as:在我的单元测试中,我将 EF Core 2.2 与InMemoryDatabase一起使用,例如:

var dbOptions = new DbContextOptionsBuilder<MyContext>().UseInMemoryDatabase("Foo").Options;
using (var context = new MyContext(dbOptions));
{
    // Do stuff..
}

When using UseInMemoryDatabase do I really need to dispose the DbContext ?使用UseInMemoryDatabase ,我真的需要处理DbContext吗? After reading Jon Gallants blog I realize that Dispose() isn't always needed even when using a real SQL database provider.阅读Jon Gallants 博客后,我意识到即使使用真正的 SQL 数据库提供程序,也不总是需要Dispose() What is the point of disposing the DbContext when using an InMemoryDatabase?使用 InMemoryDatabase 时处理DbContext有什么意义? Can I leave it to GC?我可以把它留给GC吗?

As long as the context has no dependencies like a db connection or file resources that should be freed on dispose, you can leave out the dispose.只要上下文没有依赖关系,比如应该在处置时释放的数据库连接或文件资源,你就可以省略处置。

All the references that go out of scope get marked for garbage collection automatically.所有超出范围的引用都会自动标记为垃圾收集。

By the looks of your code you have a using block which in my opinion is a good thing because as soon as the running code leaves your using block, Dispose get called.从代码的外观来看,您有一个using块,在我看来这是一件好事,因为一旦运行代码离开您的using块,就会调用Dispose

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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