I'm trying to process DB migrations during application startup in a Azure-hosted web API. However, no matter where I try to put it, I get the exception:
ObjectDisposedException: Cannot access a disposed object.
I gather that this is because I'm wrapping the context Migrate call in a "using" statement during the wrong part of the injection process. But I'm not sure where it should be located.
I've consulted the following articles:
- ASP - Core Migrate EF Core SQL DB on Startup
- https://jasonwatmore.com/post/2019/12/27/aspnet-core-automatic-ef-core-migrations-to-sql-database-on-startup
- https://blog.rsuter.com/automatically-migrate-your-entity-framework-core-managed-database-on-asp-net-core-application-start/
And have tried the following migration locations:
public Startup(IConfiguration appSettings)
{
using var dbContext = new MyContext();
dbContext.Database.Migrate();
}
This produced the ObjectDisposedException on MyContext. So I tried removing it from the constructor and adding it to services and injecting it into the configure call (per the first and second articles):
public Startup(IConfiguration appSettings)
{
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyContext>();
[...]
}
public void Configure(IApplicationBuilder app,
IWebHostEnvironment env, MyContext dbcontext)
{
[...]
dbcontext.Database.Migrate();
}
This also produced the ObjectDisposedException on MyContext. So I tried changing how the configure method access the context service (per the third article):
public Startup(IConfiguration appsettings)
{
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyContext>();
[...]
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
[...]
using var serviceScope = app.ApplicationServices
.GetRequiredService<IServiceScopeFactory>()
.CreateScope();
using var context = serviceScope.ServiceProvider
.GetService<MyDbContext>();
context.Database.Migrate();
}
Which still produced the ObjectDisposedException on MyContext.
I would appreciate any help in understanding what I'm doing wrong trying to implement this EF Core migration! Thanks!