Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Blazor Server App and IDbContextFactory not disposing

I have a blazor server application that needs to indirectly connect to a EF core DB context.

None of the blazor components will directly inject an instance of the dbcontext. I am using mediator which will handle all business operations.

The documentation that I have seen so far recommends using IDbContextFactory. I gave it a try but I am not seeing the DbContext created by the factory being disposed. The services that inject IDbContext are not disposed on page changes nor at any other time.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class QueryHandler : IQueryHandler<Query, Entity>, IDisposable
{
    private readonly DbContext dbContext;

    public QueryHandler(IDbContextFactory factory)
    {
        dbContext = factory.CreateDbContext();
    }

    public Task Handle(Query query)
    {
       /// do whatever needs to be done.
    }
  
    public void Dispose()
    {
        dbContext.Dispose(); // <-- Dispose never gets called.
    }
}

Am I missing something?

>Solution :

The purpose of using a DbContextFactory is to have a DbContext per method.
Exactly because Blazor doesn’t offer useful Scopes to handle this.

public class QueryHandler : IQueryHandler<Query, Entity> //, IDisposable
{
    ...

    public QueryHandler(IDbContextFactory factory)
    {
        _factory = factory;
    }

    public Task Handle(Query query)
    {
       using dbContext = _factory.CreateDbContext();

       /// do whatever needs to be done.
    }
  
    //public void Dispose() { }

}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading