Cam Bruce
Cam Bruce

Reputation: 5689

Configure EF Core Context through IOptions

I have a custom workflow component that uses DI and the .NET Core options pattern, including a connection string to a backing database. I was planning on adding EF Core to do some data access to the same database and would like to use the connection string i am already setting through services.AddWorkflowEngine(), however I'm running into issues getting the connection string to EF when internally configuring the DbContext, because the connection strings are not set yet when trying to call AddDbContext<T>().

Is there an appropriate place to setup EF core so the connection string can be set internally through `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;
}

Upvotes: 4

Views: 1248

Answers (1)

Cam Bruce
Cam Bruce

Reputation: 5689

Per @Nkosi's comment, if I wanted to accomplish this, I would have to genericize my DbContext in order to inject a IOptions<WorkflowConfigurationOptions<T>>, which would introduce too much complexity at this time.

I ended up manually invoking the delegate.

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;
}

Upvotes: 1

Related Questions