Skip to content

Suggested Options pattern doesn't work for DbContextOptions #21441

@SetTrend

Description

@SetTrend

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions