DEV Community

Spyros Ponaris
Spyros Ponaris

Posted on

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

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/

Top comments (1)

Collapse
 
__b63657 profile image
nikosst

Really useful write-up, Spyros!! Great job.