We have a Web API Core application that use the EF Core with the SQL Server in a backend. I am trying to update one of the database tables whenever the Web API service starts (in a Startup.cs Configure method)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SomeDBContext dataContext, ILoggerFactory loggerFactory)
{
.......................
// Automatically perform database migration
dataContext.Database.Migrate();
PopulateSomeTable(dataContext);
}
private async void PopulateSomeTable(SomeDBContext context)
{
var someTables = context.SomeTables;
if (someTables != null && (await someTables .CountAsync()) == 0)
{
someTables .Add(new Entities.SomeTable
{
someProperty1= 20,
someProperty2 = "Something",
someProperty3 = DateTimeOffset.Now,
});
await context.SaveChangesAsync();
}
}
However, when I try to access the context I get this error
Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context
How can I fix it?
Thank you in advance