C
C#2y ago
CrosRoad95

❔ IEnumerable and dependency injection

if i want to loop enumerable from DI multiple times
var foos = services.GetRequiredService<IEnumerable<Foo>>(); // add .ToList()?
foreach(foo in foos) {}
foreach(foo in foos) {}
foreach(foo in foos) {}
var foos = services.GetRequiredService<IEnumerable<Foo>>(); // add .ToList()?
foreach(foo in foos) {}
foreach(foo in foos) {}
foreach(foo in foos) {}
is it better to first get list? My concern is that DI will look for "Foo" multiple times even if it isn't needed
14 Replies
David_F
David_F2y ago
The main point is that you should assume that it may iterate each time, so if you don't want that, then call .ToArray() on it the first time and cache it
Thinker
Thinker2y ago
You should pretty much always use ToList or ToArray when iterating an IEnumerable multiple times catsip
CrosRoad95
CrosRoad95OP2y ago
thats a good point
David_F
David_F2y ago
Depend on the contract, not on the current behavior IEnumerable contract is that it is lazily evaluated
CrosRoad95
CrosRoad95OP2y ago
i know that if i have something what produces enumerable, and something what consumes it it should not make list or array out of it i imagine it as a some kind of pipelining ( IEnumerable )
Anton
Anton2y ago
well, thing is, the DI container could already have cached it into an array (if the injection is not transient), so converting it a sceond time is just wasting memory, which is what the question is asking, I would assume need to look into the source code
David_F
David_F2y ago
@CrosRoad95 Depends on the behavior you want to implement. If your subsequent pipeline processors need fresh data each time they enumerate, then yes, you should not cache it with ToArray()
Anton
Anton2y ago
but consider that a microoptimization
CrosRoad95
CrosRoad95OP2y ago
on the other hand, in my case i have very few elements and code that doing loop multiple is executed very rarely
Anton
Anton2y ago
then you can just do it. it's gonna matter in behavior when there are transient dependencies so do call ToArray that's probably what you want what I mean is that with toarray the dependencies will be only created once, while without it it would create them on every loop lazily
Monsieur Wholesome
Am I the only one baffled by the idea of storing some IEnumerable<int> in a service container
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
Accord
Accord2y 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