Wednesday, June 16, 2010

Dependency Injection - Part 1 - Inversion of Control



Ok, what the heck is dependency injection? At first glance, it sounds like some sort of tax evasion practice or psycho-emotional encouragement. No.. it is a way to turn a programming language on itself.

Huh??

Well.. let's explain a few things: (If you don't understand object-oriented languages.. this is going to lose you quickly... sorry.)

Inversion of Control
In structured programming, and especially in event-driven models like ASP.NET, there is a certain pattern of control that is followed. Ability to contort and adjust the outcome of that flow, essentially is the very nature of programming. You ask for a form or a page, and you get it. During that flow, you interrupt the execution by adding event-handlers, and overriding base functionality. I know this is overly simplified, but you get the gist of where I am headed, hopefully.

Inversion of Control is a pattern that takes the normative method hard-instantiation of objects, and allows the programmer to remote-control the decision-making process.

Simple version:

Interface IBeverageHoldingThingy

Property Volume as Integer
Sub FillWithLiquid

End Interface

This interface can be used in multiple implementations to define certain attributes of an implemented class. Note the difference in the console-write:


Class WaterTank
Implements IBeverageHoldingThingy
 
Public Sub FillWithLiquid() Implements IBeverageHoldingThingy.FillWithLiquid
Console.WriteLine("I am filled with {0} gallons of liquid", Volume)
End Sub
 
Public Property Volume As Integer Implements IBeverageHoldingThingy.Volume
 
End Class
Class TeaCup
Implements IBeverageHoldingThingy
 
Public Sub FillWithLiquid() Implements IBeverageHoldingThingy.FillWithLiquid
Console.WriteLine("I am filled with {0} cups of liquid", Volume)
End Sub
 
Public Property Volume As Integer Implements IBeverageHoldingThingy.Volume
 
End Class

Thus far the examples are following a standard control pattern. If we wanted to invert the control, we could reflect on the classes for a given assembly, and try to find out which implement the IBeverageHolderThingy interface, and then make a logically informed decision to determine which, in a collection of IBeverageHolderThingy objects we want to use.


Sub New()
Dim Asm As Assembly = Assembly.GetExecutingAssembly
Dim types = From i In Asm.GetTypes 
Where (i.IsInterface = False 
                   And TypeOf (i) Is IBeverageHoldingThingy)
'Do some funky logic with the types...
End Sub

This is an inverted control, because it turns to look at the assembly and make informed decisions on implementation.

Next: Dependency Injection - Part 2 - Working with Dependencies

No comments:

Post a Comment