See https://github.com/aspnet/EntityFrameworkCore/issues/1906#issuecomment-374352462
Here are the test results that I got.

The CacheTestClassXXX classes use a simplified version of the work around described in https://github.com/aspnet/EntityFrameworkCore/issues/1906#issuecomment-374320307.
Notice that only CacheTestClass1 had the overhead of DbContext model creation.
But the TestClassXXX classes all had the overhead.
public abstract class TestBase : IDisposable
{
private readonly SqliteConnection _connection;
protected readonly DbContextOptions
public TestBase()
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
_options = new DbContextOptionsBuilder
.UseSqlite(_connection)
.Options;
using (var context = new DbContext(_options))
{
context.Database.EnsureCreated();
}
}
public void Dispose()
{
_connection.Close();
}
[Fact]
public void DummyTestMethod() { }
}
public class TestClass1 : TestBase { }
public class TestClass2 : TestBase { }
public class TestClass3 : TestBase { }
[Collection(nameof(DbContextCache))]
public class CacheTestClass1 : TestBase { }
[Collection(nameof(DbContextCache))]
public class CacheTestClass2 : TestBase { }
[Collection(nameof(DbContextCache))]
public class CacheTestClass3 : TestBase { }
[CollectionDefinition(nameof(DbContextCache))]
public class DbContextCache : ICollectionFixture
microsoft.entityframeworkcore.sqlite v2.0.2
xunit v2.3.1
xunit.runner.visualstuio v2.3.1
.NET Framework 4.6.1
VS 2017 15.6.1
Windows 7
cc: @ajcvickers
@gojanpaolo I was able to reproduce this. The issue is that xunit (or the runner) is creating a new app domain for each test collection. This can be good for isolation, but does defeat EF caching. I believe that there are options to turn of this behavior in xunit, so that might be cleaner than what you have above. Also, when running on .NET Core there are no app domains, so xunit will never have this behavior there. (Unless they simulate it with multiple processes or something like that.) Closing as there is no EF actionable issue here.
For more info on how to configure xunit not to use appdomains
https://xunit.github.io/docs/configuring-with-json
@ajcvickers I see. Thank you for taking the time to look into this. :)
@smitpatel Awesome! Thanks for the link.
Most helpful comment
For more info on how to configure xunit not to use appdomains
https://xunit.github.io/docs/configuring-with-json