我已经写了ServiceCollection
的扩展名,我想在其中配置EntityFramework Core配置和相应的DbContext。通过json文件加载配置。现在,我正在努力的部分是,我想将我的IInstanceConfiguration
映射到我的OracleConfiguration
作为完整实例。我当前的解决方案如下所示。
我在想知道实现此方法的正确(更好)方法的地方添加了两个注释。
亲切的问候!
public static void RegisterEfCoreOracle<T>(this IServiceCollection services, string configurationDirectory, string configurationFile) where T : DbContext
{
//Adding configuration file
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(configurationDirectory)
.AddJsonFile(configurationFile, optional: false)
.Build();
services.Configure<OracleConfiguration>(configuration);
//Do i really have to do it manually this way? What would be another, elegant way?
var oraInstance = new OracleConfiguration(configuration.GetValue<string>("Name"), configuration.GetValue<string>("DataSource"), configuration.GetValue<string>("UserId"),
configuration.GetValue<string>("Password"),configuration.GetValue<bool>("UseConsoleLogging"), configuration.GetValue<string>("Compatibility"));
//This is the line where I am struggling.
services.AddSingleton<IInstanceConfiguration, OracleConfiguration>(oraInstance);
var oraConfig = services.ReturnServiceProvider().GetRequiredService<OracleConfiguration>();
services.AddDbContext<T>();
}
public static ServiceProvider ReturnServiceProvider(this IServiceCollection services) => services.BuildServiceProvider();
答案 0 :(得分:0)
var oraInstance
行是完全不必要的,services.Configure<OracleConfiguration>(configuration);
行应按预期设置依赖项注入。
如果要注入的类型是特定的IInstanceConfiguration
而不是具体的OracleConfiguration
,则可以这样注册:
services.AddSingleton<IInstanceConfiguration>(sp =>
sp.GetRequiredService<OracleConfiguration>());
否则,如果您可以控制要注入的类型,则最好完全删除IInstanceConfiguration
接口,并使其接受IOptions<OracleConfiguration>
。