In EF Core, how does configuring a DbContext in OnConfiguring differ from passing DbContextOptions<TContext> to its constructor, and can the two be combined?
answer
- options built outside vs inside
- OnConfiguring runs for every instance
- optionsBuilder.IsConfigured
- DbContextOptions<TContext> per context type
- protected ctor with non-generic options
basics
~20 sConstructor options are built outside the context, by DI or a DbContextOptionsBuilder<TContext>, and passed in; OnConfiguring builds them inside the class. OnConfiguring still runs when options were passed, so the two combine, and IsConfigured tells it a provider is already set.
solid answer
~40 sWith constructor options the context declares `public NewsContext(DbContextOptions<NewsContext> options) : base(options)`, and whoever creates it decides the provider and connection, which is what lets tests swap in SQLite. `OnConfiguring(DbContextOptionsBuilder)` is a virtual method called once for each context instance, before first use, with a builder seeded from the constructor options, so it can add to them. `optionsBuilder.IsConfigured` is true when a database provider is already configured, letting `OnConfiguring` supply a fallback only. Take the generic `DbContextOptions<TContext>`: options for a different context type make the constructor throw `InvalidOperationException`, and only a base class meant for inheritance should take the non-generic `DbContextOptions` in a protected constructor.
code
csharp · 16 linespublic abstract class ContentContextBase : DbContext
{
protected ContentContextBase(DbContextOptions options) : base(options) { }
}
public sealed class NewsContext(DbContextOptions<NewsContext> options)
: ContentContextBase(options)
{
public DbSet<Article> Articles => Set<Article>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
optionsBuilder.UseSqlite("Data Source=news-dev.db");
}
}go deeper
Recall the two options sources: a constructor taking DbContextOptions<TContext>, or an OnConfiguring override that calls a provider method such as UseNpgsql.
Explain that OnConfiguring still runs after constructor options, what IsConfigured checks, and why the generic options type prevents mixing up two contexts.
Show the pooling constraints: options frozen, OnConfiguring run once per pooled instance and forbidden to change options, so per-request state moves elsewhere.
Weigh a shared base context for several bounded contexts against independent contexts, and how option ownership affects testing and provider swaps.
## Two places to configure a context Every EF Core context needs **options**: at minimum a database provider and connection (`UseNpgsql`, `UseSqlServer`, `UseSqlite`), plus optional settings such as the default query tracking behaviour or interceptors. The options end up in an immutable **`DbContextOptions`** object, and EF Core offers two ways to produce it. | | Constructor options | `OnConfiguring` | |---|---|---| | Where options are built | Outside the class, by DI or a `DbContextOptionsBuilder<TContext>` | Inside the class | | Who chooses the provider | The caller | The context itself | | Swapping providers in tests | Easy: pass different options | Hard: the choice is inside the class | | How often it executes | Built once, then shared | Once for each new instance | ### Constructor options ```csharp public class NewsContext(DbContextOptions<NewsContext> options) : DbContext(options) { public DbSet<Article> Articles => Set<Article>(); } var options = new DbContextOptionsBuilder<NewsContext>() .UseNpgsql(connectionString) .Options; await using var db = new NewsContext(options); ``` The options object is built once and can be shared by every instance. Dependency-injection registration builds it the same way and passes it in; that registration is the web-app side of the story and is covered with per-request contexts. ### OnConfiguring `protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)` is called **for each context instance**, the first time the instance needs its internal services. The base implementation does nothing. A console tool or a quick sample often puts `optionsBuilder.UseNpgsql(...)` here and creates the context with `new NewsContext()`. ## They combine The constructor taking `DbContextOptions` documents that **`OnConfiguring` will still be called** to allow further configuration. EF hands `OnConfiguring` a builder seeded with the constructor options, so: - it can **add** settings to whatever the caller passed; - `optionsBuilder.IsConfigured` returns `true` when a **database provider** is already among the options, so `OnConfiguring` can supply a fallback provider only when the caller did not; - a provider configured in both places is configured twice, which is rarely what you meant. ```csharp protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) optionsBuilder.UseSqlite("Data Source=news-dev.db"); } ``` ## Generic or non-generic options 1. A context that is not meant to be subclassed should take **`DbContextOptions<TContext>`**. Options carry their context type, and the `DbContext` constructor throws `InvalidOperationException` when it receives options built for a different context type. With two context types in one container, a non-generic `DbContextOptions` parameter is how that happens. 2. A base context meant for inheritance exposes a **protected** constructor taking the non-generic `DbContextOptions`, so each concrete subclass can pass its own `DbContextOptions<TSubclass>` up the chain. The `DbContext` base constructor itself is non-generic for exactly this reason. 3. A context that declares only a parameterless constructor ignores any options a registration supplies; EF's registration methods throw `ArgumentException` when they see configuration passed to such a context. ## Interaction with pooling With context pooling, EF builds the options once, freezes them, and reuses each context instance across requests. Two consequences: - `OnConfiguring` runs only once per **pooled instance**, when it is first created, so it cannot carry per-request state such as a tenant id; - if `OnConfiguring` tries to change the frozen options, EF throws `InvalidOperationException` ("'OnConfiguring' cannot be used to modify DbContextOptions when DbContext pooling is enabled"). ## Testing and ownership Constructor options make the **caller** the owner of the provider choice, and that is what testing needs: - an integration test builds `new DbContextOptionsBuilder<NewsContext>().UseNpgsql(testConnectionString).Options` against a throwaway database and constructs the context directly; - a fast test can pass SQLite options instead, while production code never changes; - a context that hard-codes `UseNpgsql(...)` in `OnConfiguring` without an `IsConfigured` guard either silently replaces the test's connection or, when the test passed SQLite options, adds a second provider, which EF rejects at first use because only a single database provider can be registered. The options object itself is **immutable**. Each `Use...` call on a builder produces a new options instance, so one `DbContextOptions<NewsContext>` can safely be shared by every context created from it, across threads, while each context instance stays single-threaded. ## Choosing - Application code with dependency injection: constructor options, with nothing in `OnConfiguring`. - Small tools without a container: `OnConfiguring` is acceptable, but read the connection string from configuration rather than hard-coding it. - Libraries and shared base contexts: a protected non-generic constructor plus generic constructors on the concrete types.
- Two contexts, NewsContext and AuditContext, both declare a constructor taking non-generic DbContextOptions. What goes wrong?The container can hand one context the options built for the other. Options remember their context type, and the `DbContext` constructor throws `InvalidOperationException` saying the options passed must be a `DbContextOptions<NewsContext>`. The fix is a `DbContextOptions<TContext>` parameter on each concrete context, keeping the non-generic parameter only on a protected base-class constructor.
- Why can OnConfiguring not set a per-request tenant id on a pooled context?A pooled instance runs `OnConfiguring` only once, when the pool first creates it, and the pool's options are frozen. Later requests get the same instance back without another `OnConfiguring` call, so per-request state must be set after renting it, typically by a scoped wrapper around `IDbContextFactory<TContext>`.
- Passing options to the constructor stops OnConfiguring from being called.
- OnConfiguring runs once per application, like a static initialiser.
- IsConfigured is true whenever any option at all has been set.
- Every context should take the non-generic DbContextOptions so subclasses can reuse it.
- OnConfiguring on a pooled context is a good place to set the current tenant id.