Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static dependency injection factory, right or wrong?

I very recently have hit a brick wall when I gave a shot at Ninject in the project I'm working on.

I have went through all kind of questions, systematically requestionning my design and architecture in favour of dependency injection.

  1. Is this right to inject the container/kernel to the main application presenter?

  2. How to configure Ninject to use along with NHibernate in WinForms?

  3. Conditional dependency injection binding only when property not null

  4. What did I get wrong, DI or Design, and how should I go about it?

After hours, and hours, and hours of searching, I came across that article from Justin Etheredge who speaks of his static DIFactory class.

  • Creating a binding factory for Ninject

I now wonder, is it not making things work like magic using a static DI factory?

I'd like to hear pros and cons of using a static DI factory in a real-world application.

Also, are IoC and DI the same, or are they very similar, though some differences?

like image 747
Will Marcouiller Avatar asked Apr 02 '14 05:04

Will Marcouiller


1 Answers

A static DI Factory is a Service Locator, and a Service Locator is an anti-pattern because it will make it difficult to reason about your code:

  • It breaks encapsulation.
  • It violates the Interface Segregation Principle.
  • It makes it more difficult to spot violations of the Single Responsibility Principle.
  • It makes object composition more difficult, because it hides the composition context from the Service Locator.
  • It breaks the Hollywood Principle.

The only advantage of Service Locator is that it's slightly easier to understand than Dependency Injection. However, DI isn't that hard to grasp once you get over a few conceptual hurdles.

The relationship between IoC and DI is that DI is a special case of IoC.

like image 64
Mark Seemann Avatar answered Oct 15 '22 06:10

Mark Seemann