Thursday, August 30, 2007

Objectbuilder

ObjectBuilder is a framework for creating dependency injection systems.
It allows to customize how an object is created.
To support component independence, a componenent must be able to use another component without requiring a change to the source code of the component to be used.
It using attributes CreateNew and ServiceDependency.

working with ObjectBuilder
1. Creating new Objects
2. Locating a service
3. Registering a service
4. Registering a constructor

Creating New Objects
The NewTransferView class requires an instance of the NewTransferViewPresenter class but does not contain code to instantiate an instance. Instead, the NewTransferView class uses the CreateNew attribute.
[CreateNew]
public NewTransferViewPresenter Presenter
{
get { return _presenter; }
set
{
_presenter = value;
_presenter.View = this;
}
}
The CreateNew attribute instructs ObjectBuilder to instantiate and initialize an instance of a NewTransferViewPresenter when the NewTransferView is created. When the property is set, the View property of the presenter is used to connect this implementation of the INewTransferView interface to the presenter (the View property is defined in the Presenter base class).


Locating a Service

You can add the ServiceDependency attribute to a property in your class to declaratively obtain a reference to a service. The property specifies the type of service or interface you require, as shown in the following code. When this attribute is present, ObjectBuilder locates an instance of the service and passes back a reference to it. To locate the service, ObjectBuilder first looks in the current WorkItem. If the service is not found, ObjectBuilder then looks at the services in the parent WorkItem. If the service is not found, ObjectBuilder throws an exception.
private IAccountServices _accountServices;

[ServiceDependency]
public IAccountServices AccountServices
{
set { _accountServices = value; }
}

Registering a Service

You can programmatically register a service. To do this, call the Add method or AddNew method of the Services collection of the WorkItem within which you want to use the service. This can be the root WorkItem or a module WorkItem. To use an existing service instance you have already created, use the Add method.
moduleWorkItem.Services.AddNew();

Registering a Constructor

A class can contain more than one constructor. ObjectBuilder first looks for any constructor decorated with the [InjectionConstructor] attribute (there can be only one of these) and uses this constructor if found. If there is no decorated constructor, yet there is only one constructor, it will use that constructor.
public class CustomersListViewPresenter
{
private CustomersController _controller;

[InjectionConstructor]
public CustomersListViewPresenter ( [ServiceDependency] CustomersController controller)
{
_controller = controller;
}
...
}

No comments: