【发布时间】:2021-02-09 02:45:21
【问题描述】:
我有一个使用 DI 和 .NET Core 选项模式的自定义工作流组件,包括一个到后备数据库的连接字符串。我正计划添加 EF Core 以对同一数据库进行一些数据访问,并希望使用我已经通过 services.AddWorkflowEngine() 设置的连接字符串,但是在内部配置时我遇到了将连接字符串获取到 EF 的问题DbContext,因为在尝试调用AddDbContext<T>() 时尚未设置连接字符串。
是否有合适的位置设置 EF 核心,以便可以通过 `AddWorkflowEngine() 在内部设置连接字符串?
WorkflowEngine.cs
public class WorkflowEngine<TScheme> where TScheme : WorkflowScheme
{
public WorkflowEngine(IOptions<WorkflowConfigurationOptions<TScheme>> options)
{
this.connectionString = options.ConnectionString;
}
}
Extensions.cs
public static IServiceCollection AddWorkflowEngine<TScheme>(this IServiceCollection services,
Action<WorkflowConfigurationOptions<TWorkflowScheme>> optionsAction)
where TScheme : WorkflowScheme
{
service.TryAddScoped<WorkflowEngine<TScheme>>();
services.Configure(optionsAction);
return services;
}
【问题讨论】:
-
你不需要 IOptions。可以在 Startup 中使用
AddDbContext时配置上下文 -
WorkflowConfigurationOptions的通用性质使其难以与AddDbContext重载一起使用,这将允许您在延迟配置委托中解析IOption
标签: c# .net-core dependency-injection entity-framework-core