Search code examples
.net-coreentity-framework-coredisposeidisposable

necessity of Dispose method mocking EF core with the in memory provider


Background

I'm working on a asp.net core application that uses Entity Framework Core as it's orm. For unit testing I'm using microsoft's in memory provider (Microsoft.EntityFrameworkCore.InMemory specifically version 1.1.0) to manually mock the database with a class that is derived from my DBContext.

MockDBContext.cs:

public class MockDBContext:DBContext{
    public MockDBContext:base(
        new DbContextOptionsBuilder<DBContext>().UseInMemoryDatabase(
            Guid.NewGuid().ToString()
        ).Options
    ){}
    public override void Dispose(){}
    public void clear(){
        base.Dispose();
    }
}

where a new unique in memory database is created for each context.

I'm currently overriding Dispose to do nothing to allow me to check values written by the target methods, which have using(DBContext... inside them, otherwise checking would throw a ObjectDisposedException when I run the assert in my tests. I currently have another method called clear that I can manually call that calls base.Dispose in MockDBContext.

Question

My question is, since the mock database is in memory, do I actually need to dispose it? or will it get garbage collected if I don't bother with calling clear inside a try finally for each test


Solution

  • As long as your Memory db context no dependencies like a db connection or file resources that should be freed on dispose, you can leave the dispose empty. All references that are out of scope will be collected automatically when there is no reference to the object.