I'm running some unit tests on an asp.net core 2.0 project, using EF core and an in-memory database.
I'm creating the database like this:
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
var builder = new DbContextOptionsBuilder<TDatabaseContext>();
builder.UseInMemoryDatabase(Guid.NewGuid().ToString())
.UseInternalServiceProvider(serviceProvider)
.EnableSensitiveDataLogging();
var context = new MyDatabaseContext(builder.Options);
According to this post (How to isolate EF InMemory database per XUnit test), using a separate service provider and using a different name for every in-memory DB instance should ensure that each test has its own database which is not shared with other tests.
However, my tests run fine when I run them separately, but fail if I run them all together, with errors like this:
System.InvalidOperationException: The instance of entity type 'SomeModelObject' cannot be tracked because another instance with the key value 'Id:1' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
Is there anything else I should do to make sure that the DB context is not shared among different tests?