从我为EF找到的数据库拦截器中可以看出,它们必须使用Startup.cs
方法在AddInterceptors
中注册。此方法接收实例,使拦截器成为单例。
我需要在拦截器中注入一个作用域服务,这样是不可能的。
有没有办法向DbContext
中添加作用域db拦截器?
services.AddDbContext<DatabaseContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString(...)
.AddInterceptors(new DatabaseLogIntgerceptor());
发布于 2020-09-26 15:48:13
此方法接收实例,使拦截器成为单例。
实际上不是单身,而是限定范围的。
AddDbContext
有几个过载,所有参数都有两个可选参数
contextLifetime容器中注册
DbContext
服务的生存期。 optionsLifetime容器中注册DbContextOptions
服务的生存期。
两者都默认为ServiceLifetime.Scoped
。optionsLifetime
还控制调用选项配置操作的范围。
所以在默认情况下
.AddInterceptors(new DatabaseLogIntgerceptor())
将按每个作用域调用,从而可以在其中注入作用域服务。
至于如何做到这一点,您必须使用AddDbContext
重载和动作接收IServiceProvider
,并解析服务(或保护器),例如
services.AddDbContext<DatabaseContext>((sp, options) => options
.UseSqlServer(
Configuration.GetConnectionString(...)
)
.AddInterceptors(
sp.GetRequiredService<DatabaseLogInterceptor>()
)
);
https://stackoverflow.com/questions/64078656
复制相似问题