Microsoft documentation suggests to use the Options pattern so configuration settings can be used from within Startup::ConfigureServices().
I, however, don't seem to be able to get the suggested approach to be working:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.Configure<ApiConfiguration>(Configuration) // copy configuration settings into ApiConfiguration
.AddDbContext<DataContext>() // create DbContext and use connection string from configuration
.AddOptions<DbContextOptionsBuilder>().Configure<IOptionsSnapshot<ApiConfiguration>>((dbOptions, config) => dbOptions.UseSqlServer(config.Value.ConnectionStrings?.SqlServer));
}
When I use the DataContext class (derived from DbContext) served by Dependency Injection, the DbContextOptions set in the Lambda expression are not taken into account.
Adding a breakpoint to the lambda expression following AddOptions() I can see that it's not getting called.
For testing purposes I added a DataContext parameter to Startup::Configure(), so Dependency Injection instantiates an object for me:
public void Configure(DataContext ctx)
{ ... }
This should have triggered the creation of the DbContextOptions object from the Lambda expression. However, it doesn't.
Is the documentation valid for objects derived from DbContext, too? What's the suggested approach for DbContext derived objects?
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
Microsoft documentation suggests to use the Options pattern so configuration settings can be used from within
Startup::ConfigureServices().I, however, don't seem to be able to get the suggested approach to be working:
When I use the
DataContextclass (derived fromDbContext) served by Dependency Injection, theDbContextOptionsset in the Lambda expression are not taken into account.Adding a breakpoint to the lambda expression following
AddOptions()I can see that it's not getting called.For testing purposes I added a
DataContextparameter toStartup::Configure(), so Dependency Injection instantiates an object for me:This should have triggered the creation of the
DbContextOptionsobject from the Lambda expression. However, it doesn't.Is the documentation valid for objects derived from
DbContext, too? What's the suggested approach forDbContextderived objects?Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.