我在使用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
自动将依赖项注入到服务提供程序中 - 因为它本身可以完美地工作。这个错误很令人困惑,因为内存数据库就是我想要使用的提供程序。