When IDbContextFactory enters the chat, and what it actually fixes.

Leader posted 1 min read

When IDbContextFactory enters the chat, and what it actually fixes

Most EF Core examples use a scoped DbContext. In a normal Web API request, that’s fine, the request ends, the context is disposed.

Then you build Blazor Server.

A Blazor Server circuit can stay alive for a long time, minutes or hours. If your DbContext is scoped, it can also stay alive that long. That’s when things start to break in annoying ways.

What problems show up

1) “A second operation was started on this context…”
DbContext is not thread-safe. In Blazor Server it’s easy to trigger overlapping work (clicks, timers, loading states). If two queries happen at the same time on the same context, you get this error.

2) Tracking bloat
A long-lived context keeps tracking entities. Over time:

  • memory grows
  • queries can feel slower
  • SaveChanges can get heavy
  • you hit “already being tracked” errors

3) Stale or confusing data
Because the context tracks objects, you can end up reusing old instances without realizing it, the UI feels out of sync.

What IDbContextFactory changes

It gives you a fresh DbContext per operation.

  • create context
  • run the query or command
  • dispose the context

So each click, each load, each action gets its own clean context. No shared state, no concurrency fights, no growing tracker.

When to use it

Use IDbContextFactory when you have:

  • Blazor Server
  • background jobs or hosted services
  • timers, polling, signalR style event flows
  • any parallel DB work

In simple controller-per-request apps, scoped DbContext is still perfectly fine.

The takeaway

IDbContextFactory is not a “nice to have”, it’s the safer default when your app is long-lived and event-driven. It prevents a whole category of EF Core bugs before they happen.

Source Code :

https://github.com/stevsharp/BlazorFactoryDemo

More to read :

https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.idbcontextfactory-1?view=efcore-10.0

https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/

1 Comment

1 vote
0
0

More Posts

When to Use AsSplitQuery() in EF.core

Spyros - Feb 26, 2025

EF Core Bulk Updates and Deletes: Performance vs Change Tracking

Spyros - Mar 24, 2025

EF Core: Lazy Loading, Eager Loading, and Loading Data on Demand

Spyros - Mar 6, 2025

⚔️ The Mighty MERGE: Using SQL Merge Statements Safely with EF Core

Spyros - Jul 25, 2025

How to Bind a MudSelect from an External Source in Blazor Using MudBlazor

Spyros - Apr 10, 2025
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

2 comments
2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!