Dependency Injection Semantics

An entry about inversion of control Publication date 4. May 2009 16:21

So you’ve decided to follow the dependency inversion principle, and have your dependencies injected (maybe by some container). Surely whether you use constructor or setter injection is a matter of personal choice, yes?

I don't think so.

Consider the restriction that a constructor argument imposes on the creation of your class – the argument is implicitly a required dependency because you can’t make your code compile if you can’t provide it (well sure, you can pass in a null value, but then you’re explicit about it). Property setters on the other hand, carry no such implications. And this is important to recognize and take advantage of, because code which carries obvious, unambiguous semantics is much, much easier to work with.

Update: To clarify, my recommendation is that you always prefer constructor injection for required dependencies, and only consider using property injection for optional dependencies.

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.


Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS