Skip to content

DbContext Lifetime, Configuration doesn't align with Options pattern #3098

@SetTrend

Description

@SetTrend

The page doesn't align with another MS docs page, describing the ASP.NET Core Options pattern.

The hard-coded examples on the page are informative, yet don't reflect real business situation where connection string is provided by ASP.NET (Core) configuration.

I'm missing a description in either documentation on how to use the Options pattern with AddDbContext.

\ref: dotnet/AspNetCore.Docs/issues/21441


To give more detail:

services.Configure<ApiConfiguration>(_config)
  .AddDbContext<DataContext>(options => options.UseSqlServer(_config.Get<ApiConfiguration>().ConnectionStrings?.SqlServer, providerOptions => providerOptions.EnableRetryOnFailure()));

... works, yet dependency injection should be used for configuration:

services.Configure<ApiConfiguration>(_config)
  .AddDbContext<DataContext, ApiConfiguration>((options, config) => options.UseSqlServer(config.ConnectionStrings?.SqlServer, providerOptions => providerOptions.EnableRetryOnFailure()));

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

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions