Sunday, November 4, 2012

Dependency injection for smarties

Till the last week I was thinking that dependency injection is a rather simple thing and mostly is about resolving a component by its interface/base class with some nuances like providing additional information as name, constructor signature, transient/singleton instance, etc. Almost everyone among my friends wrote their own implementation of IoC container, that's not big deal. They differ one from another by name of main method (Get/Resolve/Whatever) and internal implementation, but all they were about was simple component resolving and no more.

However, last week I was diving deep in autofac IoC container and one thing in their documentation just made me rethink all that I knew about the relationships between the components (actually, I didn't think of anything except the first type from the list). Here is what they call relationships:

Relationship Constructor signature Meaning
A needs B A(B b)Dependency
A needs B at some point in the future A(Lazy<B> b)Delayed instantiation
A needs B until some point in the future A(Owned<B> b)Controlled lifetime
A needs to create instances of B A(Func<B> b)Dynamic instantiation
A provides parameters of types X and Y to B A(Func<X,Y,B> b)Parameterisation
A needs all the kinds of B A(IEnumerable<B> b)Enumeration
A needs to know X about B A(Meta<T> b) and A(Meta<B,X> b)Metadata interrogation

More on the relationships you can read in the dedicated article Relationship Zoo, highly recommended. I hope it will make you rethink what DI was meant for you.

No comments:

Post a Comment