Blazor Server - DbContext is disposed after refreshing page blazor blazor-server-side entity-framework entity-framework-core


I am developing a Blazor server app, where all clients will have a list of things, any one of these clients can update thing which should then trigger a callback telling all clients to call DbContext.Entry(thing).Reload() so they're up to date. This works all great and well until I refresh the page, then I get the Cannot access a disposed object error and I can't figure out how to get around it.

I have the follow services:



public class RefreshService {
    public Func<long, Task> OnRefreshThing { get; set; }

    public void RefreshThing(long thingId) => OnRefreshThing?.Invoke(thingId);


protected override void OnInitialized() {
    RefreshService.OnRefreshIssue += OnRefreshIssue;
private async Task OnRefreshThing(long thingId) {
    // This works perfectly until I refresh the page & try to call it again
    Thing thing = await MainDbContext.Things.FindAsync(thingId); // exception is thrown here

    await MainDbContext.Entry(thing).ReloadAsync();

And here's an example of what triggers the error:

Thing thing = Things.Where(t => t.ThingId == 1);
thing.Name = "New name";
4/8/2020 8:35:39 PM

Popular Answer

  1. You can modify the RefreshService to be Scoped not Singleton
  2. The AddDbContextPool does not dispose the instance of the dbcontext completely, it resets the instance to its default state and it could be because of the reset that it can't access it again
4/9/2020 9:54:50 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow