我正在使用带有SQL Server的EF Core和IOC的StructureMap编写ASP.Net Core Web API。
库项目均为.NetStandard2.0
,而API和单元测试均为NetCoreApp2.0
。
对于单元测试,我正在运行XUnit并将SQL Server换成内存中的SQLite数据库,因为它提供了完全参照完整性。 我仍在使用与主要代码相同的IOC设置,但是我传入了一个结构映射注册表列表,以使我可以替代SQLite上下文工厂而不是sql。
这是我的DbContext的精简版:
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions options) : base(options)
{
}
}
这是我的测试设置代码:
public IServiceProvider ServiceProvider { get; set; }
public MyServiceTests()
{
var services = new ServiceCollection();
var dataRegistry = new Registry();
dataRegistry.For<IContextFactory<MyDbContext>>().Use<SqlLiteContextFactory>();
if (SqlLiteContextFactory.Connection == null)
{
SqlLiteContextFactory.Connection = new SqliteConnection("DataSource=:memory:");
SqlLiteContextFactory.Connection.Open();
}
services
.AddEntityFrameworkSqlite()
//This is only here as some posts suggested this was needed, StartUp.cs for production site does not have this and works fine.
.AddDbContext<MyDbContext>(options => options.UseSqlite(SqlLiteContextFactory.Connection));
var registries = new List<Registry>
{
dataRegistry,
new CommandQueryRegistry(),
new ServiceRegistry(),
new TransformRegistry()
};
ServiceProvider = DependencyInjection.TestSetup(services, registries);
}
IOC初始化代码非常基本:
public static IServiceProvider TestSetup(IServiceCollection services, List<Registry> registries)
{
var container = new Container();
var registry = new Registry();
registries.ForEach(r => registry.IncludeRegistry(r));
container.Configure(config =>
{
config.AddRegistry(registry);
config.ForSingletonOf<IHttpContextAccessor>().Use<HttpContextAccessor>();
config.Populate(services);
});
var serviceProvider = container.GetInstance<IServiceProvider>();
return serviceProvider;
}
这是我的SQLite上下文工厂的上下文工厂代码,它与SQL的唯一区别是我具有静态的Connection
属性,以确保在处理完上下文后不会丢失数据库
public class SqlLiteContextFactory : IContextFactory<MyDbContext>
{
public static SqliteConnection Connection;
private DbContextOptions<MyDbContext> CreateOptions(bool trackChanges)
{
var builder = new DbContextOptionsBuilder<MyDbContext>();
var optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
optionsBuilder.UseSqlite(Connection);
if (!trackChanges)
{
builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
}
return builder.Options;
}
private MyDbContext CreateDbContext(bool trackChanges)
{
if (Connection == null)
{
Connection = new SqliteConnection("DataSource=:memory:");
Connection.Open();
}
var context = new MyDbContext(CreateOptions(trackChanges));
//Always keep context as most recent version in tests
context.Database.Migrate();
return context;
}
public MyDbContext CreateNonTrackedContext()
{
return CreateDbContext(false);
}
public MyDbContext CreateDbContext()
{
return CreateDbContext(true);
}
}
我的代码在运行站点时运行良好,SQL上下文工厂创建了上下文,并运行migration命令创建数据库没有问题。
但是,当我尝试通过单元测试来测试我的任何服务时,尝试使用以下命令运行Migrate
时上下文工厂会崩溃:
System.InvalidOperationException : No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext.
at Microsoft.EntityFrameworkCore.Internal.DbContextServices.Initialize(IServiceProvider scopedProvider, IDbContextOptions contextOptions, DbContext context)
at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.GetRelationalService[TService](IInfrastructure`1 databaseFacade)
at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
at API.Test.Utilities.SqlLiteContextFactory.CreateDbContext(Boolean trackChanges) in API.Test\Utilities\SqLiteContextFactory.cs:line 37
at API.Test.Utilities.SqlLiteContextFactory.CreateDbContext() in API.Test\Utilities\SqLiteContextFactory.cs:line 49
at API.CommandQueries.Commands.MyCommand.AddOrUpdate(MyModel model) in \API.CommandQueries\Commands\MyCommand.cs:line 21
at API.Services.MyService.Save(Model model) in API.Services\MyService.cs:line 40
at API.Test.MyTests.CanAdd() in API.Test\MyServiceTests.cs:line 47
我已经尽力解决此问题。将.AddDbContext
添加到服务集合中。确保测试项目和上下文项目都引用了EntityFrameworkCore
,EntityFrameworkCore.Relational
和EntityFrameworkCore.Sqlite
。确保SQLite连接保持活动状态,并确保测试设置在.AddEntityFrameworkSqlite()
上使用ServiceCollection
。
我还尝试过用另一个上下文工厂将SQLite换成EF Cores InMemory
Db,但是失败的原因完全相同。
在使用EF Core之前,是否有人以某种方式使其与SQLite不兼容?
答案 0 :(得分:0)
我前一段时间对此进行了研究。而且我相信您需要运行迁移并保持连接打开。您正在覆盖静态连接。另外,在使用连接之前,我不确定是否已创建它。