Blazor, Object Life Time and Dependency Injection

Viewed 219

I'm working on my first Blazor project, and I'm facing a issue about object life time.

The exact problem is that my EF DbContext never get disposed, so after first database update, any subsequent update fail because of a exception telling me that the entity is already tracked by the context.

So after investigation, I've discover that all Dependency Injected service are resolved when the app get launched and never get disposed so are the DbContext which is injected as a UnitOfWork

In MVC, the end point object get disposed any time the call ends, so DbContext gets disposed, and this issue never occurs.

But in Blazor object life time are different. As a good practice should I manually get resolve the DbContext when needed, or did a miss something?

EDIT: I should also add that my DbContext is added to IServiceCollection as Scoped

1 Answers

Blazor does not have the convenient Request scopes that a Server has.

You should manage the Context yourself, you can't leave it (entirely) to the DI.

This page shows you how to either

  • manage the context in method scope, with using( ... )
  • or link it to the Component lifetime with @implements IDisposable

In both cases you can use a DbContextFactory (standard issue in EF5) to create it while using the registered config options.

So never inject the DbContext itself.

Related