JustAMartin
JustAMartin

Reputation: 13733

Confusion about DI, IoC and service locators

I have read various articles about IoC, DIP, DI and Service Locators but I'm a bit confused which is which because some articles have too vague examples and some other articles have just some specific examples without mentioning other cases.

Could you please clear this up for me, looking at the examples below and shortly explaining which examples match which pattern?

Upvotes: 1

Views: 294

Answers (2)

Facio Ratio
Facio Ratio

Reputation: 3393

Everything you listed is a form of Dependency Injection.

  1. "Poor Man's" DI
  2. DI using an IoC container
  3. "Poor Man's" DI again. DI works whether you are using an interface or an abstract class.
  4. Method Injection
  5. I'm not sure what you're asking here. It sounds like you want to change the instance of IWorld at runtime, which might be a case for Property Injection instead of Constructor Injection. Properties are oft used for optional dependencies or those that can change. Whether you then set that dependency at run-time with a Service Locator or other means is up to you. Another thing to consider is that IWorld might just depend on context, in which case you could do a context-depdendent constructor injection, the details of which are beyond the scope of this question.
  6. Not related to DI

Upvotes: 2

MikeSW
MikeSW

Reputation: 16348

Every time you pass a dependency as a constructor/method argument, that's Dependecy Injection. It can be manual, like in most of your examples, or automatic using a DI Container aka IoC Container.

Using a container means the objects using deps are constructed by the container. You could ask the container directly for that service and in that case, there's a static property or method ( think DependecyResolver in asp.net mvc) that exposes that service. In that case you're using the Service Locator pattern. IWork in your example is not a locator, it's just a dependency.

To continue with the dependency resolver example, you register all relevant types into a container, the container is build then registered as the dependency resolver. The asp.net mvc framwork then uses the resolver (the Service Locator - SL) to instantiate controllers, views and all the deps these require.

To use the SL pattern is ok as part of a framework, but it's not ok if you're using it in your app to instantiate objects, because it couples the code to the locator. Sometimes is the only solution but 99% you is just an anti-pattern.

Upvotes: 1

Related Questions