Dependency Patterns


Scott Bellware has an excellent post on dependency injection patterns.  By far this has been a concept that I struggle with in explaining to other developers.

When I first heard of frameworks such as Sprint.Net, Windsor, StructureMap, it took me a while to grasp their usefulness.  I simply saw them as a strategy for making testing easier.  I had know idea the benefit they would lend to my architecture.  The ability for an IoC container to resolve my dependencies automatically, simply from a configuration file is genius. 

The difficult part is wrapping your head around the intended behavior of the “transparent” dependency.  As you inject a transparent dependency into class, you must expect it to behave a certain way when the consuming class acts upon it.  By using Mock objects in place of the physical dependent class you can evolve an interfaces intention upon the acting class through proper TDD testing. I know, I know show us the code.  I will, just really busy right now with work!  I struggle to find how Ayende is able to find the time in the day to work and blog.  I am truly not a blog Jedi yet.

I posed the following question to Scott as a joke but he gave and excellent response.

” I was wondering what a property injection would be called. Perhaps “Translucent Dependency” “

Scott’s reply

“Joe,

Property injection is still a transparent dependency.  Properties are typically used for lessor and infrastructural dependencies, like logging, if they’re used at all.

They’re good for the things that don’t have to do with the class’s main concern. The dependencies that are property-injected would muddy the constructor signature with ancillary plumbing and cloud the principal purpose of creating an instance of the class.

If the dependency isn’t something that’s key to solving the concrete business scenario that the class serves, it likely shouldn’t be a constructor argument.  By making it a property, it can still be assigned (like an instance of ILogger, for example), but it doesn’t obscure the primal intension of an instance.

Setter dependencies are optional.  Their types should have a Null Object pattern implementation, and if not it’s often a good idea to decorate them with one.  For example, if an optional dependency hasn’t been set, it might not be desirable to have a null reference exception when a method is invoked on it.  Optional dependencies reserve the right to not be assigned to by the very nature of them not being mandatory or primal constructor arguments.”

Behavior Driven Design with NUnit User Group Presentation – Level 100