The Programmator

Tired of Dependency Injection bloated constructors?

Dependency Injection is an undisputable necessity when writing testable code. It’s also a great way of forcing you to Program to Interfaces, rather than concrete class implementations. However, when the solution gets bigger, the dependency graph grows with it. And even though we all try to keep our layers neatly separated (that is, if you’re developing in a traditional multi-tier-style), with every new class comes a new Interface and another dependency in the constructor. This also means that every unit test using a constructor injection will now need its parameter list updated (that is, if you’re not using any AutoMocking feature). Agreed that thirty-odd injections in your class make it smell like a God-Object, yet sometimes classes need a lot of logic/data resources to do validation. There has to be a better way!

Too long dependency injection constructor does not solve tight coupling

MediatR as a silver bullet?

I’d known the mediator pattern for a while, but never really bumped into a pragmatic use of it. Until recently, when I started working on a new assignment which spans multiple business domains in a distributed environment. Each domain has quite a bit of code separated in a Domain service, (External) Services and Repositories. Instead of creating the Dependency Injection of Hell constructor, all calls are handled by MediatR using an implementation of a Request, which returns a Response. I was amazed at the ease of use and implementation! Kudos for that Jimmy Bogard!

Great, where’s the code?

For the project, we added a layer on top of MediatR to facilitate the CQRS way of working. Below you can find a (non-compiling) snippet as to how that would look.

Interface definitions:

Basic sample implementation:

All further code samples can be found on the MediatR Git repo.

 

I’d love to know if you tried it and how that went.

Happy coding!

Like what you read? Maybe your friends do too! Share this article:

Leave a Reply