At what point does activation of services happen in Ninject when requesting IEnumerable

StackOverflow https://stackoverflow.com/questions/16647426

  •  30-05-2022
  •  | 
  •  

Frage

We are using Ninject in work as part of a modification to our legacy system. In some parts of the application we have opted to use a static Service Locator that wraps around Ninject. This is really only a static adapter.

When I request IEnumerable<IFoo> via our Service Locator it simply requests the same via Ninject's GetAll method. What I wanted to know is since I haven't actually enumerated the list, will all services remain inactive.

The reason I am asking is we are using Ninject to replace an old controller locator in a WinForms app. Some of these controllers are hairy so I don't want them activating until I have filtered to the one I want. How we are doing this is applying a Where clause to the collection on the service locator and then using FirstOrDefault to pick the correct one.

My understanding is that the activation will happen on enumeration (in our case at FirstOrDefault) is this correct?

War es hilfreich?

Lösung

You are correct that the GetAll doesn't actually do anything until you enumerate it in some manner. When you ask for an IEnumerable, each item pulled brings it to life - even if it's about to be filtered by a Where (the only way it could is if IQueryable were involved).

Each item Activated, will be Deactivated in line with the normal scoping rules.

The best way to avoid this is by having a .When... or other condition dictating the filtering.


DO NOT READ PAST THIS POINT - BAD ADVICE FOLLOWS.

A mad Hack is to request an IEnumerable<Lazy<T>> (which will require Ninject.Extensions.Factory). Good related article.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top