C# 通过IOptions配置EF核心上下文
我有一个自定义工作流组件,它使用DI和.NET核心选项模式,包括到备份数据库的连接字符串。我计划添加EF Core以对同一数据库进行一些数据访问,并希望使用我已通过C# 通过IOptions配置EF核心上下文,c#,.net-core,dependency-injection,entity-framework-core,C#,.net Core,Dependency Injection,Entity Framework Core,我有一个自定义工作流组件,它使用DI和.NET核心选项模式,包括到备份数据库的连接字符串。我计划添加EF Core以对同一数据库进行一些数据访问,并希望使用我已通过服务设置的连接字符串。AddWorkflowEngine(),但是在内部配置DbContext时,我遇到了将连接字符串获取到EF的问题,因为在尝试调用AddDbContext()时,尚未设置连接字符串 是否有适当的位置设置EF core,以便可以通过'AddWorkflowEngine()'在内部设置连接字符串 WorkflowEng
服务设置的连接字符串。AddWorkflowEngine()
,但是在内部配置DbContext时,我遇到了将连接字符串获取到EF的问题,因为在尝试调用AddDbContext()
时,尚未设置连接字符串
是否有适当的位置设置EF core,以便可以通过'AddWorkflowEngine()'在内部设置连接字符串
WorkflowEngine.cs
public class WorkflowEngine<TScheme> where TScheme : WorkflowScheme
{
public WorkflowEngine(IOptions<WorkflowConfigurationOptions<TScheme>> options)
{
this.connectionString = options.ConnectionString;
}
}
public static IServiceCollection AddWorkflowEngine<TScheme>(this IServiceCollection services,
Action<WorkflowConfigurationOptions<TWorkflowScheme>> optionsAction)
where TScheme : WorkflowScheme
{
service.TryAddScoped<WorkflowEngine<TScheme>>();
services.Configure(optionsAction);
return services;
}
公共类工作流引擎,其中TScheme:WorkflowScheme
{
公共工作流引擎(IOOptions选项)
{
this.connectionString=options.connectionString;
}
}
Extensions.cs
public class WorkflowEngine<TScheme> where TScheme : WorkflowScheme
{
public WorkflowEngine(IOptions<WorkflowConfigurationOptions<TScheme>> options)
{
this.connectionString = options.ConnectionString;
}
}
public static IServiceCollection AddWorkflowEngine<TScheme>(this IServiceCollection services,
Action<WorkflowConfigurationOptions<TWorkflowScheme>> optionsAction)
where TScheme : WorkflowScheme
{
service.TryAddScoped<WorkflowEngine<TScheme>>();
services.Configure(optionsAction);
return services;
}
公共静态IServiceCollection AddWorkflowEngine(此IServiceCollection服务,
行动选项(行动)
where TScheme:WorkflowScheme
{
service.TryAddScoped();
服务。配置(选项操作);
返回服务;
}
根据@Nkosi的评论,如果我想做到这一点,我必须将我的DbContext
泛化,以便注入IOptions
,这将在此时引入太多的复杂性
我最终手动调用了委托
public static IServiceCollection AddWorkflowEngine<TScheme>(this IServiceCollection services,
Action<WorkflowConfigurationOptions<TWorkflowScheme>> optionsAction)
where TScheme : WorkflowScheme
{
service.TryAddScoped<WorkflowEngine<TScheme>>();
// manually invoke action
var options = new WorkflowConfigurationOptions<TScheme>();
optionsAction.Invoke(options);
services.AddDbContext<WorkflowDbContext>(dbOptions=>
dbOptions.UseSqlServer(options.ConnectionString);
services.Configure(optionsAction);
return services;
}
公共静态IServiceCollection AddWorkflowEngine(此IServiceCollection服务,
行动选项(行动)
where TScheme:WorkflowScheme
{
service.TryAddScoped();
//手动调用操作
var options=新工作流配置选项();
optionAction.Invoke(选项);
services.AddDbContext(dbOptions=>
使用SQLServer(options.ConnectionString);
服务。配置(选项操作);
返回服务;
}
您不需要IOptions。您可以在启动时使用AddDbContext
来配置上下文WorkflowConfigurationOptions
的一般性质将使其难以与AddDbContext
重载一起使用,而该重载将允许您在延迟配置中解析IOption
埃列盖特