I am trying use InMemory EF7 database for my xunit repository test.
But my problem is that when i try to Dispose the created context the in memory db persist. It me
From the documentation,
Typically, EF creates a single
IServiceProviderfor all contexts of a given type in an AppDomain - meaning all context instances share the same InMemory database instance. By allowing one to be passed in, you can control the scope of the InMemory database.
Instead of making the test class disposable and trying to dispose the data context that way, create a new one for each test:
private static DbContextOptions CreateNewContextOptions()
{
// Create a fresh service provider, and therefore a fresh
// InMemory database instance.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
// Create a new options instance telling the context to use an
// InMemory database and the new service provider.
var builder = new DbContextOptionsBuilder();
builder.UseInMemoryDatabase()
.UseInternalServiceProvider(serviceProvider);
return builder.Options;
}
Then, in each test, new up a data context using this method:
using (var context = new DatabaseContext(CreateNewContextOptions()))
{
// Do all of your data access and assertions in here
}
This approach should get you a squeaky-clean in-memory database for each test.