dependency injection – Is there a proper way of implementing runtime control of dependencies using DI? Is factory pattern okay?

I’m currently brushing up and learning about a bunch of techniques to hopefully begin implementing in my own workflow; one of which is IoC (and DI in particular).

I’m hoping someone could clear up my confusion I have reading two articles about the subject:

In this post, the author seems to demonstrate that you can use the factory pattern alongside DI, with the goal of enabling runtime control of which implementation of the dependency is used.

In this Microsoft doc, they seem to recommend avoiding this approach (or rather, to avoid mixing it and any service locator pattern, with DI). I’m not sure if this means there’s always a better alternative, or rather to simply avoid it in most scenarios but there might be some exceptions where there’s merit (e.g. runtime control).


I guess another potential view at the question could be: when using DI, should runtime control of dependencies be avoided just as much as mixing with service locator pattern, as to reduce the need for things like service locator pattern?

I’m writing this with pretty much no experience using DI yet, so apologies if I’m somehow missing the big picture.