In my
last post I showed how you can use the InjectionMethod attribute to have a method called after the object is instantiated. Of course this will not happen if you simply new your object, but instead you have to use
ObjectBuilder to instantiate the object. Now I thought I show you just a simple example of how you instantiate objects with ObjectBuilder.
Builder builder = newBuilder();
SimpleClass o = builder.BuildUp<SimpleClass>(null, null, null);
Builder is an implementation of IBuilder<TStageEnum> and uses all the default strategies shipped with ObjectBuilder. The strategies that is shipped with ObjectBuilder is TypeMappingStrategy, SingletonStrategy, ConstructorReflectionStrategy, PropertyReflectionStrategy, MethodReflectionStrategy, CreationStrategy, PropertySetterStrategy, MethodExecutionStrategy and BuilderAwareStrategy.
The three arguments to this overload of BuildUp is locator, idToBuild and existing. It is also possible to call the method with policies which is a parameter array as the last argument. The locator is a lifetime container that stores a reference to the objects to control the management and disposal of the objects. I guess I will come back to this in a post on more advanced building. The idToBuild isn't either of so much interest if you haven't provided any locator since it is used to identify an object. This can be used to get an existing object, at least that is what I think, but I'm not sure because if haven't test this so much yet. The existing parameter is used if you want to run an existing object through the strategies pipeline and for example have the method marked with InjectionMethod called. I don't see when you would want to do this, but I haven't been using DI so much, so that could change.
Anyway, the point is that it doesn't have to be difficult to use ObjectBuilder instead of just newing the objects. To finish this up I could show you a short example of the other overload for BuildUp method too. This is very useful if you for example have a configuration file with the name of the class you want to create. Here I have hardcode the name of the class for simplicity.
Builder builder = new Builder();
Type t = Type.GetType("ObjectBuilderLab.SimpleClass, ObjectBuilderLab");
SimpleClass o = builder.BuildUp(null, t, null, null) as SimpleClass;
Of course the example would be more realistic if the variable o was declared as some type of interface or base class. One I come to think of immediately is that the variable is a Form which should be shown as a result of a user clicking a menu item or similar.