Wednesday, March 2, 2016

Book Review: Dependency Injection in .NET

Dependency Injection in .NET changed the way I think about software development. Dependency injection is a topic that is easy to describe, but not until reading this book did I feel it in my bones as I was writing code. It's a powerful topic. Here are my main takeaways from reading this excellent book.

Use constructor injection - not setter injection. Constructor injection is the cleanest way of passing dependencies. This way, it is known when you have an instance of that class the dependency has been specified. Otherwise with setter injection guard clauses must be added to ensure the dependency has been set (besides as we know, mutation is the devil!)

Make your code testable - unit tests help ensure correctness. A side benefit of writing testable code is loose coupling where components have no knowledge of how the surrounding system works. This enables changing the program easier in the future. If you start with this principle when designing your application you will end up with much cleaner design resulting in fewer defects.

.NET Containers - the last part of the book goes over the most popular .NET dependency injection containers. I'm not going to go over them in detail here, but castle windsor, structuremap, and spring .NET are among the containers covered in the book. Good patterns and anti-patterns when using these containers are discussed with clear examples. I was surprised at the extensive features provided by these libraries.

Even non OO and non .NET programmers can benefit from the ideas in this book. These patterns remind me of good functional code, where the program is made up of mostly pure functions that are easily testable. Passing dependencies and settings into functions instead of defining them within the function is a great way to write applications.

No comments:

Post a Comment