I have a db context in a Blazor server-side and I'm registering with default values:
services.AddDbContext<AppContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("App"));
});
This db context is registered as a scoped service. I also use repository pattern and my repositories are transient. Using this setup changes are tracked and saved as expected. However once deployed I was getting sporadic exceptions:
An exception occurred while iterating over the results of a query for context type 'AppContext'. System.InvalidOperationException: A second operation was started on this context instance before a previous operation completed. This is usually caused by different threads concurrently using the same instance of DbContext. For more information on how to avoid threading issues with DbContext,
So I changed the lifetime to transient by doing:
services.AddDbContext<AppContext>(options =>
{
options.UseSqlServer(configuration.GetConnectionString("App"));
}, ServiceLifetime.Transient);
With this single change, changes are not being tracked and there is nothing to save.
What am I missing?