Skip to content
This repository has been archived by the owner on Nov 2, 2018. It is now read-only.

The scoped instance referenced by the singleton can't be disposed!!! #475

Closed
ZhiqiangTao opened this issue Jan 19, 2017 · 5 comments
Closed

Comments

@ZhiqiangTao
Copy link

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?

@ZhiqiangTao
Copy link
Author

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.

@khellang
Copy link
Contributor

khellang commented Jan 19, 2017

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).

@ZhiqiangTao
Copy link
Author

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 👍

@ZhiqiangTao
Copy link
Author

@khellang thanks for your explanation.

@Eilon
Copy link
Member

Eilon commented Jan 31, 2017

@ZhiqiangTao using a short-scope service from a longer-scoped service will always be problematic, so the recommendation is to avoid this pattern.

@Eilon Eilon closed this as completed Jan 31, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants