Cannot access a disposed object in ASP.NET Core when injecting DbContext

Just a guess in what causes your error:

You are using DI and async calls. If, somewhere in your call stack, you return a void instead of Task, you get the described behavior. At that point, the call is ended and the context disposed. So check if you have an async call that returns a void instead of Task. If you change the return value, the ObjectDisposedException is probably fixed.

public static class DataSeedExtensions {
private static IServiceProvider _provider;

public static async Task SeedData(this IApplicationBuilder builder) { //This line of code

  _provider = builder.ApplicationServices;
  _type = type;

  using (Context context = (Context)_provider.GetService<Context>()) {

    await context.Database.MigrateAsync();
    // Insert data code

  }

}

And in configure:

if (hostingEnvironment.IsDevelopment()){
   await  applicationBuilder.SeedData();
}

Blog post on how to fix this error: Cannot access a disposed object in ASP.NET Core when injecting DbContext

Leave a Comment