0

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?

Ivan Debono
  • 457
  • 3
  • 14
  • `Transient` means a new instance on every creation of a dependent type. So `Transient` `DbContext` in a transient repository means you may get multiple instances of `DbContext` during the request. Changes made on one instance are not accessible by another. Instead of changing the `DbContext` lifetime, ensure you are not accessing it concurrently by multiple threads. – Artur Aug 05 '23 at 19:35
  • See - https://learn.microsoft.com/en-us/ef/core/dbcontext-configuration/ and one of many SO answers: https://stackoverflow.com/questions/67374706/blazor-server-mixing-ef-core-dbcontextfactory-with-dbcontext. Basically, use a `DbContextFactory` for your contexts. – MrC aka Shaun Curtis Aug 05 '23 at 21:40
  • . . . or just use Dapper. Make a query, run the query, get your results, move on with your life. – Bennyboy1973 Aug 05 '23 at 22:21

0 Answers0