❔ IEnumerable and dependency injection
if i want to loop enumerable from DI multiple times
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
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
You should pretty much always use
ToList
or ToArray
when iterating an IEnumerable multiple times thats a good point
Depend on the contract, not on the current behavior
IEnumerable contract is that it is lazily evaluated
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 )
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
@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()
but consider that a microoptimization
on the other hand, in my case i have very few elements and code that doing loop multiple is executed very rarely
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
Am I the only one baffled by the idea of storing some IEnumerable<int> in a service container
they might've meant this https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.dependencyinjection.serviceproviderserviceextensions.getservices?view=dotnet-plat-ext-7.0
ServiceProviderServiceExtensions.GetServices Method (Microsoft.Exte...
Get an enumeration of services of type serviceType from the IServiceProvider.
Unknown User•2y ago
Message Not Public
Sign In & Join Server To View
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.