C
C#14mo ago
CrosRoad95

❔ Garbage collection question

I see in many libraries examples where in DI ".AddScoped<>", ".AddTransient<>" is used instead of ".AddSingleton<>", example in fluent assertions example says: services.AddScoped<IValidator<User>, UserValidator>(); and i wonder why? this class instance is sorto "read only" so it could be singleton? And here's my question regarding that, because singleton will create long lived instanced meanwhile the other two will live for let's say 100ms, they will be regularly cleared, less often reach further generation. I know that not all singletons are used at all time, they will live in memory for long time and cause extra pressure on garbage colletor. What do you think? is it better to use Transient/Scoped even when singleton make sense from memory point of view?
4 Replies
Angius
Angius14mo ago
Mind you, singleton services cannot use scoped or transient ones singleton -> scoped -> transient direction works transient -> scoped -> singleton does not So, perhaps, UserValidator requires some scoped service, that's why it cannot be a singleton
CrosRoad95
CrosRoad95OP14mo ago
true too
IsNotNull
IsNotNull14mo ago
I find that many junior or mid tier application developers have a poor understanding of DI scopes and they often use transient or scoped because it causes the fewest issues and side effects. (e.g. doesn't conflict with the scoped DbContext dependencies). If you use singleton you have to organize that dependency like its stateless or global (with its concurrency safety issues). I also regularly see ambivalence from team members about garbage creation outside of hot loops...and if we're being honest it often does not create any issues. Many apps are IO / database bound. I'll prefer singleton whenever it makes sense, but I don't bother bringing the concept up with team mates very often anymore unless they ask.
Accord
Accord14mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server