简体   繁体   中英

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:

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 ? After reading Jon Gallants blog I realize that Dispose() isn't always needed even when using a real SQL database provider. What is the point of disposing the DbContext when using an InMemoryDatabase? Can I leave it to 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.

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