EntityFramework.Docs icon indicating copy to clipboard operation
EntityFramework.Docs copied to clipboard

Please add code sample

Open TRegan3 opened this issue 3 years ago • 1 comments

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.

TRegan3 avatar Mar 04 '22 13:03 TRegan3

or by registering the DbContext as transient

This statement is aimed at typical ASP.NET Core applications that use dependency injection. It may or may not be relevant when writing other kinds of D.I. applications. We should make that cleared. Beyond that, I'm not sure the EF docs are the best place to talk about all the potential pitfalls with D.I. and threading--that would be better suited to the docs for writing Windows services.

ajcvickers avatar Mar 04 '22 16:03 ajcvickers