I recently asked about doing DI properly, and got some links to blog posts about it. I think I have a better understanding now - separate object construction from logic, by putting it in factories. But all of the examples are for things like websites, and say to do all the wiring at startup. Call one large factory which new
s everything and passes in all the dependencies.
But what if I don't want to instantiate everything up front? I have an object which contains a list of other objects which it can delegate to, but they are expensive, and used one at a time, so I construct them when needed and let them get collected when I'm done. I don't want to put new B()
inside the logic of A
because I would rather use DI - but how? Can A
call the factory? That doesn't seem much better, unless the factory is maintaining state including the current dependencies. I just don't want to pass the full list of B
s into A
when it's constructed, since it would be wasteful. If you want, B
doesn't necessarily have to be inside A
, although it makes logical sense (A
is a game level, B
is a single screen), but in any case the logic of A
dictates when B
is created.
So, who calls the factory to get B
, and when?
Clarification: I'm not using framework for DI. I wonder if the term DI implies that?