You may have heard of the service locator in the spring framework. Now there are many predecessors who think that Service Locator is an anti-pattern. In fact, service Locator is a concrete implementation of dependency lookup. Although the idea of service locator and dependency injection are essentially opposites, MS.DI uses the service locator when implementing the dependency injection framework.

If you haven’t used spring, it’s okay.

Let us try to clarify the relationship between the two. Obviously, Dependency Injection is mainly about injecting. There is a very interesting answer on Dependency Injection on Stack Overflow. The question is how to explain dependency injection to a five-year-old child:

When a child goes and gets things out of the refrigerator by themselves, they might create problems. They might leave the door open, or might get something Mommy or Daddy doesn’t want them to have. They might even be looking for something they don’t even have or which has expired.

What they should be doing is stating a need, “I need something to drink with lunch,” and then the parent will make sure they have something when they sit down to eat.

So the right approach is to ask the children what they need, then we will find something from the refrigerator and find out and hand it to them.

To make an analogy, children taking out things from the refrigerator is similar to dependency lookup; when we provide things to children as adults, this is dependency injection.

Before discussing dependency injection in detail, I think we need to review the five principles of design patterns (some places mention six or even seven, but these overlap the basic five), Part 2 in this series will go through the first couple of these principles