Do I need to Dispose DbContext when using an InMemoryDatabase?

c# entity-framework-core

Question

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?

1
1
1/31/2019 6:57:06 AM

Accepted Answer

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.

1
1/31/2019 12:23:02 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow