如何在.NET依赖注入中使用两个独立的MongoDB数据库



我有两个MongoDB数据库,想在Worker Service类中使用:

services.Configure<DbConnectSetting>(
hostContext.Configuration.GetSection("fwkConfiguration:DataBase1Settings"))
.AddTransient<IDbConnectSetting>(s =>
s.GetRequiredService<IOptions<DbConnectSetting>>().Value)
.AddTransient(typeof(IRepository<>), typeof(Repository<>))
.AddTransient(typeof(IDB1Repository), typeof(DB1Repository));
services.Configure<DbConnectSetting>(
hostContext.Configuration.GetSection("fwkConfiguration:DataBase2Setting"))
.AddTransient<IDbConnectSetting>(s =>
s.GetRequiredService<IOptions<DbConnectSetting>>().Value)
.AddTransient(typeof(IRepository<>),typeof(Repository<>))
.AddTransient(typeof(IDB2Repository), typeof(DB2Repository));

但问题是,它总是为工作类中的对象实例最后创建DB2值,是否需要解决采取单独值的问题。

尝试为选项命名。检查此文档

类似于:

services.Configure<DbConnectSetting>("DB1" ,...);  
services.Configure<DbConnectSetting>("DB12 ,...);
// Usage
public Foo(IOptionsSnapshot<DbConnectSetting> options){
options.Get("DB1");

最新更新