Skip to content

Please add code sample #3754

Open
Open
@TRegan3

Description

@TRegan3

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions