-2

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.

1
  • 1
    Questions on this site should ideally be self-contained, without the need to read the external references they link to. That's because external links often get invalid over time. I guess this one here is on the edge of not being really understandable in full any more without the external references.
    – Doc Brown
    Commented May 11, 2021 at 20:08

1 Answer 1

2

Run time control of dependencies is a good thing. It makes your code flexible and enables testing. Your objects can still be immutable and you can still start with known good default values. Just make them overridable. Remember construction time is still run time.

What you want to avoid is statically binding objects together. Do that and you wasted your time making them two different objects. The only way to break them apart is to rewrite their code.

That’s why we don’t like the Service Locator Pattern. It’s the same kind of binding. Just on the locator. It’s better if you don’t know where your dependencies come from or what your IoC container is since a service locator is a dependency as well.

This doesn't mean you can't use a IoC container. It just means you want to isolate knowledge of it. Do that and you wont simply be reinventing the service locator pattern.

The best article I can recommend to illustrate this idea is Uncle Bob's Dependency Injection Inversion. It's in Java but that's not that different from C#. He shows you how to do all this with Googles IoC container: Guice.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.