5

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.

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?

Community
  • 1
  • 1
Will Marcouiller
  • 23,773
  • 22
  • 96
  • 162

1 Answers1

7

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:

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.

Community
  • 1
  • 1
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • What if certain types cannot be instantiated on application startup, because they need user credentials to instantiate correctly? For instance, the `NHibernante.ISessionFactory` is such problem as it can't be instantiated without a proper connection string, and once created, it won't let one change its connection string. As a workaround, one can supply an `IDbConnection`, and loses the second level cache which holds traces of an object throughout the `ISession` lifecycle. Then one would need the user to provide his credentials, and now the `ISessionFactory` dependency is no longer a problem. – Will Marcouiller Apr 02 '14 at 06:32
  • Would it be an `AbstractFactory` which would allow new types to be registered? How would you go about it? – Will Marcouiller Apr 02 '14 at 06:41
  • 1
    If you can't resolve a sub-graph at run-time, you can always add another layer of indirection. An Abstract Factory would be one option. Here's more information about [implementing an Abstract Factory](http://blog.ploeh.dk/2012/03/15/ImplementinganAbstractFactory). – Mark Seemann Apr 02 '14 at 06:43