Description
A code sample here for the "DbContext threading issues" section would be very useful. I say that as a person who has just spent hours searching for some sample code, as I'm completely unfamiliar with scope factories. But I was able to figure it out.
Your statement "or by registering the DbContext as transient" appears to be inaccurate. Are you saying that I must use a scope factory or set the DbContext to a transient lifetime? If so, I've been unable to figure out how to do the "or" part. A code sample that explains the "or" condition would be very valuable here.
I hit the threading issue you describe when I created a multi-threaded Windows service that uses Dependency Injection. I was able to solve the problem by using a scope factory to retrieve my DbContext instead of injecting it in the usual fashion. The DbContext service lifetime can be either Scoped or Transient when retrieved with a scope factory, but merely setting the lifetime of the DbContext to transient without the scope factory leads to the DbContext threading error.
I'm creating a Windows console app that runs as a Windows service, in Visual Studio 2022 .Net 6, using the Worker project template, which creates the windows service in a class called Worker that derives from the BackgroundService class. I'm calling AddHostedService() on Worker, and then calling UseWindowsService() on the HostBuilder. In the Worker ExecuteAsync method I create an array of 3 Tasks that do the work and call WaitAll on them.
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: 055bb8db-139d-beb5-61c1-47cf1ea6ea93
- Version Independent ID: b0a3d5ad-b62c-1ff4-386a-f11e350eea0c
- Content: DbContext Lifetime, Configuration, and Initialization - EF Core
- Content Source: entity-framework/core/dbcontext-configuration/index.md
- Product: entity-framework
- Technology: entity-framework-core
- GitHub Login: @ajcvickers
- Microsoft Alias: avickers