Tuesday, April 21, 2009

StructureMap and Fluent Interface

Recently I have been working a project to process data. The case is very simple. It reads data from database, process data and finally out put data to either database or text file. I have worked on the similar scenario for many cases. This time, I decided to design a generic pattern for developing similar type applications.

Based on past experience, I think I need a dependency framework for decoupling components and integrating various implementations of interfaces into a specific application. StructureMap got my attention. After about one investigation, I really like this framework. It is just for DI but very powerful. One interesting feature of this tool is its code-based registration to map DIs, which is based on Fluent Interface.

After reading the definition and examples of Fluent Interface, I really like its readability feature. Just coming up to my mind, I envision its implementation of mapping database element to domain object.

For example, the following is a domain class as Employee:

public class Employee {
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public datetime BOD { get; set; }
public float Salary { get; set; }
}


My employee reader interface is based on Fluent Interface like this:

interface IEmployeeReaderFluent {
IEmployeeReaderFluent ReadID(IDataReader);
IEmployeeReaderFluent ReadFirstName(IDataReader);
IEmployeeReaderFluent ReadLastName(IDataReader);
IEmployeeReaderFluent ReadBOD(IDataReader);
IEmployeeReaderFluent ReadSalary(IDataReader);
Employee GetObject();
}


And the implementation class is defined as:

class EmployeeReaderFluent : IEmployeeReaderFluent {
private Employee = new Employee();
IEmployeeReaderFluent ReadID(IDataReader reader) {
Employee.ID = IDataReader.GetInt32(
IDataReader.GetOrdinal("ID"));
}
IEmployeeReaderFluent ReadFirstName(IDataReader reader) {
Employee.FirstName = reader.GetString(
reader.GetOrdinal("FirstName"));
}
IEmployeeReaderFluent ReadLastName(IDataReader reader) {
Employee.LastName = reader.GetString(
reader.GetOrdinal("LastName"));
}
IEmployeeReaderFluent ReadBOD(IDataReader) {
Employee.BOD = reader.GetDateTime(
reader.GetOrdinal("BOD"));
}
IEmployeeReaderFluent ReadSalary(IDataReader) {
Employee.Salary = reader.GetFloat(
reader.GetOrdinal("Salary"));
}
Employee GetObject() { return Employee; }
}


Example of the usages:

IEmployeeReaderFluent employeeReader = 
new EmployeeReaderFluent()
.ReadID(reader)
.ReadFirstName(reader)
.ReadLastName(reader)
.ReadBOD(reader)
.ReadSalary(reader);
Employee employeeObj = employeeReader.GetObject();

0 comments: