C# DbCommandInterceptor中的EFCore注入服务

C# DbCommandInterceptor中的EFCore注入服务,c#,entity-framework-core,C#,Entity Framework Core,从我为EF Core找到的数据库拦截器中可以看出,它们必须使用AddInterceptors方法注册到Startup.cs。此方法接收一个实例,使拦截器成为单例 我需要在拦截器中注入一个作用域服务,这样就不可能了 有没有办法将作用域数据库拦截器添加到DbContext services.AddDbContext<DatabaseContext>(options => options.UseSqlServer( Configuration.GetConne

从我为EF Core找到的数据库拦截器中可以看出,它们必须使用
AddInterceptors
方法注册到
Startup.cs
。此方法接收一个实例,使拦截器成为单例

我需要在拦截器中注入一个作用域服务,这样就不可能了

有没有办法将作用域数据库拦截器添加到
DbContext

services.AddDbContext<DatabaseContext>(options =>
    options.UseSqlServer(
        Configuration.GetConnectionString(...)
    .AddInterceptors(new DatabaseLogIntgerceptor()); 
services.AddDbContext(选项=>
options.UseSqlServer(
Configuration.GetConnectionString(…)
.AddInterceptors(新数据库登录Gerceptor());
此方法接收一个实例,使拦截器成为单例

实际上,它不是单例的,而是有范围的

AddDbContext
has,都有2个可选参数

contextLifetime 在容器中注册
DbContext
服务的生存期

选项生存期 在容器中注册
DbContextOptions
服务的生存期

这两个选项都默认为
servicelifest。Scoped
optionslifest
还控制调用选项配置操作的范围

所以默认情况下

.AddInterceptors(new DatabaseLogIntgerceptor())
将按每个作用域调用,从而可以在其中注入作用域服务

至于如何做到这一点,您必须使用
AddDbContext
重载来接收
IServiceProvider
操作,并从中解析服务(或inteceptor)

services.AddDbContext<DatabaseContext>((sp, options) => options
    .UseSqlServer(
        Configuration.GetConnectionString(...)
    )
    .AddInterceptors(
        sp.GetRequiredService<DatabaseLogInterceptor>()
    )
);
services.AddDbContext((sp,选项)=>options
.UseSqlServer(
Configuration.GetConnectionString(…)
)
.附加接收器(
sp.GetRequiredService()
)
);