ObjectBuilder is quite complex, and I have probably only scratched the surface so far, but I will try to blog a little about what I learn along the way. In this first post, I thought that I would start with a simple example of what you can do, when you write classes that are instantiated with the help of ObjectBuilder. I will start by covering the InjectionMethod and InjectionConstructor attributes.
Public Class Form1
<Microsoft.Practices.ObjectBuilder.InjectionMethod()> _
Public Sub AfterInitializeComponent()
'Do something useful ...
End Sub
End Class
When I write forms I often find myself adding an AfterInitializeComponent-method to do some additional initialization, you guessed it, after the InitializeComponent has run. Instead of adding the default constructor to my class, and from there calling my method I can instead attribute the method with InjectionMethod, which will make it called by the ObjectBuilder after the object is instantiated. Note that, for ObjectBuilder to call the method it has to be public, though.
Now, you might protest that, it’s not that much of work to add a single call to a method yourself, and of course it’s not. But this method is run after some other things have happened with your class when using dependency injection (for example after properties marked with CreateNew-attribute), and that can be very important.
The attribute InjectionConstructor is used to mark which constructor should be used by ObjectBuilder, when instantiating the class. This should be used when the class has more than one constructor, and is only allowed on one of them.
Behind the scenes ObjectBuilder uses a pipeline of strategies, where each strategy can perform operations on the object when it is instantiated. Some of the built-in strategies uses attributes to control their behavior, as shown above. For example is the ConstructorReflectionStrategy using the InjectionConstructor attribute when it determines which constructor should be used for object instantiation.