Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection best practices and anti-patterns

People also ask

Is dependency injection an anti pattern?

How come we (need to) use a runtime pattern for things we know at compile-time? if we properly registered the implementation for the respective interface. To fully use this pattern obviously MyClass has to be created as well by the DI system.

What type of design pattern is dependency injection?

In software engineering, dependency injection is a design pattern in which an object or function receives other objects or functions that it depends on. A form of inversion of control, dependency injection aims to separate the concerns of constructing objects and using them, leading to loosely coupled programs.

Which choice is best for dependency injection?

Constructor ControllerConstructor-based dependency injection is certainly considered a best practice. There was a time I personally favored setter-based injection, but I have come around to constructor-based. We can still improve our example.


I really enjoyed this article regarding DI, as it's targeted towards people who don't have a ton of DI experience, or don't even know what it is.

https://mtaulty.com/2009/08/10/m_11554/

What’s Unity?

It’s a “dependency injection container”.

Now, at that point a bunch of folks reading this will say “Yes, we know and we’re already using it for reasons A, B, C or we’ve elected not to use it for reasons X,Y,Z ” and I imagine a bunch of other folks might say;

“Huh? What’s a dependency injection container?”

This post is for the latter people – it’s not meant to be exhaustive but hopefully it’s not completely unhelpful either :-)


In my opinion, Dhanji Prasanna's book Dependency Injection is a must read for software designers, both beginners and experts. It deals directly with your DI questions.


There's a best practices section in Guice's user's guide.


I've found that when I see a violation of the Law of Demeter that is a hint that I might want dependency injection.

For example:

void doit()
{
    i += object.anotherobject.addvalue; //violation of Law of Demeter
}

Sometimes hints that I might want to dependency inject anotherobject.