builder.Services.AddDbContext<MyContext>(ServiceLifetime.Transient)? #3209
-
In a Blazor solution, sometimes I get the following error:
Is the solution |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Transient lifetime means that you get a new instance of the service each time you ask for one. Scoped lifetime means that you get a new instance of the service if there isn't already one in the current scope. Singleton lifetime means that you get a new instance of the service only once during the lifetime of the app. The local data portal creates a new scope when the code hits the logical server-side code, and disposes that scope before returning to the logical client. All server-side code executing during each data portal call runs in that scope. Generally speaking, a remote data portal call works the same way, because aspnetcore creates a scope, the server-side code runs in that scope, and the scope is disposed at the end of the call. |
Beta Was this translation helpful? Give feedback.
-
Hello @michaelcsikos , Im getting a error similar to this topic. I working on a Blazor control with pagination. May I ask how you resolved the issue? My error is below. 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, see https://go.microsoft.com/fwlink/?linkid=2097913. |
Beta Was this translation helpful? Give feedback.
Thank you.
I just realized I was using the following on my Program.cs
builder.Services.AddSingleton(s => new ASPNetContext(aspnetdb_connectionString));
so I changed it to
builder.Services.AddTransient(s => new ASPNetContext(aspnetdb_connectionString));
Thank you @michaelcsikos