【发布时间】:2017-03-27 22:32:26
【问题描述】:
我在使用 EntityFrameworkCore 时无法注入自定义 IAsyncQueryProvider。更准确地说..在使用提供的内存数据库功能时,我无法注入提供程序。使用默认提供程序 (SqlServer),一切正常。
这是我的全球Startup.cs
private void ConfigureEntityFrameworkWithSecurity(IServiceCollection services)
{
services
.AddEntityFramework()
.AddEntityFrameworkSqlServer()
.AddScoped<IAsyncQueryProvider, CustomEntityProvider>()
.AddDbContext<APIContext>((sp, options) =>
{
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.UseInternalServiceProvider(sp);
});
}
这完美地工作,我可以在CustomEntityProvider 中放置一个断点来验证它确实被注入了。目前,CustomEntityProvider 只是简单地实现了IAsyncQueryProvider,并且只是通过请求。里面没有逻辑。
当我运行测试时,我将 webhost 配置为使用不同的 Startup 文件:
public class TestStartup : Startup
{
public TestStartup(IHostingEnvironment env) : base(env)
{
}
public override void ConfigureServices(IServiceCollection services)
{
services
.AddDbContext<APIContext>((sp, options) =>
{
options.UseInMemoryDatabase()
.UseInternalServiceProvider(sp);
});
base.ConfigureServices(services);
}
}
使用TestStartup 运行测试会产生错误:
System.InvalidOperationException:没有为此 DbContext 配置数据库提供程序。可以通过重写 DbContext.OnConfiguring 方法或在应用程序服务提供者上使用 AddDbContext 来配置提供者。如果使用了 AddDbContext,那么还要确保您的 DbContext 类型在其构造函数中接受 DbContextOptions 对象并将其传递给 DbContext 的基本构造函数。
并且APIContext 的定义是正确的:
public class APIContext : DbContext
{
public APIContext(DbContextOptions<APIContext> options)
: base(options)
{
}
...
}
从TestStartup 中删除UseInternalServiceProvider 可以正常工作-但是,我不希望我的测试命中实际数据库。此外,我希望UseInMemoryDatabase 能够自动将依赖项注入到服务提供者中——因为它本身就可以很好地工作。
该错误令人困惑,因为内存数据库是我要使用的提供程序。
【问题讨论】:
标签: c# entity-framework asp.net-core entity-framework-core