In this post I'm back covering the CreateNew attribute that you can use in a class that is instantiated by
ObjectBuilder. Marking a property (or parameter to a method or constructor) with the CreateNew attributes will set that property to an instance of the object. The instance itself will of course be built by the ObjectBuilder too. A great example of when to use this functionality is if you want to implement your GUI with for example the Model View Presenter (MVP) design pattern. I will only focus on the View and Presenter here.
One positive effect of using a design pattern like MVP is that the presenter is so much more testable (with unit tests) than the GUI classes often is. The reason is of course that you don't mix your application logic with visual representation or functionality of specific controls. When using this design pattern I think it's recommended that you define an interface for the View. One big benefit with defining an interface for it is that when Windows Presentation Foundation (WPF) shows up in the end of this year and you want to upgrade your application, most of your code will stay the same since it is defined in the Presenter. The code will look something like this (and notice the CreateNew attribute on the Presenter property of the CustomerView class, that will be injected by ObjectBuilder):
public interface ICustomerView
{
//Useful things that the presenter should be able to do with the View
}
public class CustomerPresenter<T> where T : ICustomerView
{
private T view;
public T View
{
get { return view; }
set { view = value; }
}
}
public partial class CustomerView : Form, ICustomerView
{
public Form2()
{
InitializeComponent();
}
private CustomerPresenter<CustomerView> presenter;
[CreateNew()]
public CustomerPresenter<CustomerView> Presenter
{
get { return presenter; }
set
{
presenter = value;
presenter.View = this;
}
}
}
When ObjectBuilder finds the CreateNew attribute (thanks to the PropertyReflectionStrategy) it will create a new instance of the property's return type and set the value of the property to the instance (thanks to the PropertySetterStrategy). The new instance will be instantiated through ObjectBuilder of course.