I find a scenario as below:
there is a "AService" with the singleton(services.AddSingleton...) lifetime, and it need a "BRepository" also with the singleton(services.AddSingleton...) lifetime. The point is that the "BRepository" need the "dbContext" with the "Scoped" lifetime. Now when we call the "AService" to do “CURD” operation with DB many times.
the "dbContext" in the "BRepository" instance can't be disposed (just like singleton)!! but i think it should be disposed successfully!
so is't a bug or just by design? Can you answer my doubts?
Note:the operation of the "AService" will just execute one command of the DB for each time, not execute much more commands in one operation.
That's a captive dependency. When you depend on a service that has a shorter lifetime than yourself, you effectively extend their lifetime to match your own, which defeats the reason the service was registered with a shorter lifetime in the first place. This is usually a code/design smell and should be fixed either by making the whole chain scoped or depend on a factory that can provide you with scoped instances on request (and then properly dispose them when finished).
Is there any kind solution or reminding for this scenario in the feature? in the latest version of .net core?
I think that there are many coders will also meet or ignore this scenario :+1:
@khellang thanks for your explanation.
@ZhiqiangTao using a short-scope service from a longer-scoped service will always be problematic, so the recommendation is to avoid this pattern.
Most helpful comment
That's a captive dependency. When you depend on a service that has a shorter lifetime than yourself, you effectively extend their lifetime to match your own, which defeats the reason the service was registered with a shorter lifetime in the first place. This is usually a code/design smell and should be fixed either by making the whole chain scoped or depend on a factory that can provide you with scoped instances on request (and then properly dispose them when finished).