根据要覆盖的方法,您会在方法定义中收到CommandEventData
对象,该对象具有DbContext
作为属性。
关于服务和配置,您可以在注册之前配置拦截器。
代替这个:
services.AddDbContext<MySqlContext>(options => options
.UseMySql(Configuration.GetConnectionString("MySql"))
.AddInterceptors(new MySqlInterceptor()));
你可以做
var interceptor = new MySqlInterceptor(service1,service2 ... etc);
services.AddDbContext<MySqlContext>(options => options
.UseMySql(Configuration.GetConnectionString("MySql"))
.AddInterceptors(interceptor))
如何解析拦截器实例:
如果您需要自动连接拦截器的依赖项,则可以执行以下操作
services.AddTransient<Service1>();
services.AddTransient<Service2>();
services.AddTransient<MySqlInterceptor>();
// resolve the instalce of the interceptor
var serviceProvider = services.BuildServiceProvider();
var interceptor = serviceProvider.GetService<MySqlInterceptor>();
// configure mysql context and interceptor
services.AddDbContext<MySqlContext>(options => options
.UseMySql(Configuration.GetConnectionString("MySql"))
.AddInterceptors(interceptor))
,
正如@vasil在他的answer中提到的:
根据您要覆盖的方法,您将收到
方法定义中的CommandEventData对象具有
Foo
作为财产。
在我的情况下,我想解决使用另一个 DbContext的服务,事实证明这很麻烦。因此,我最终将所需的设置放入appsettings.json中,并使用DbContext
服务获取设置值并将其发送给Interceptor构造函数:
IConfiguration
注意:如果您找到了这个答案,并且正在寻找一种方法来解决services.AddDbContext<MySqlContext>(options => options
.UseMySql(Configuration.GetConnectionString("MySql"))
.AddInterceptors(new MySqlInterceptor(Configuration["SettingValue"])));
方法内的服务,而无需调用ConfigureService
,就像David Fowler所说的那样。在Github issue上,您将是:
在尝试构建容器时构建容器
您最终将拥有:
2个容器,其中一个将永远不会被丢弃。
您可以按照Nkosi在其answer中的建议进行操作:
BuildServiceProvider
本文链接:https://www.f2er.com/3105298.html