Monday, November 2, 2009

Separating layers and components with constructor injection and Unity

Ok, so how did I come to using Unity and constructor injection?

Anyway ... what is Unity? And what is constructor injection?

Unity is a "dependency injection container", (see http://www.codeplex.com/unity/ for details) in other words it is a library that implements mechanisms to easily apply the dependency injection pattern.

Dependency injection is a design pattern that aims at separating concerns, like separating from the application specific domain all the other concerns that are not strictly "about" the topic of the application (usually are more low level).

For example in a mp3 player app, connecting to the db to save personal info about the songs is not something that affects software functionality. If the db app changes or we decide that the info is going to be stored to a remote server through a web service, the functionality will still be there and the app will continue to work. It would be different if we wanted our app to be able to play iTunes audio books. That would be a change that affects the domain of the app.

So it's a valuable thing if we can separate those facet of the application from the "real" functionalities. This separation enables us to think more clearly and in a clean way about our application and not mix different concerns. Also we can unit test better and apply test driven development.

Let's see a sample app. What about the dear old "Hello world" functionality?! This app is about... saying hello... to you.. :-)
By the way this time we are going to log who are we saying hello to. How and where we are going to store this info is not really relevant to the app. We just want to able to call a method like Log(message), in the HelloWorld method of our class (MainClass, forgive the ugly name..):

public class MainClass
{
ILogger logger;

public MainClass(ILogger logger)
{
this.logger = logger;
}

public string HelloWorld(string name)
{
string helloMessage = "Hello " + name + "!";
this.logger.Log("Said hello to " + name + "!");
return helloMessage;
}
}


HelloWorld calls the Log method of an object implementing the ILogger interface. This way our application is not dependent upon a specific logger implementation, hence the inversion of dependency, the main application doesn't depend on the loggr, it's the logger that depends upon the ILogger interface defined by the app.

Here's a quick look to how the visual studio solution looks like:



It's very simple, we have a UnitySampleUse project, a MyLogger project and the test project UnitySampleUse.Test.

UnitySampleUse contains the ILogger interface. MyLogger contains MyLoggerClass that implements ILogger, so MyLogger contains a reference to UnitySampleUse. If we where going to instantiate a MyLoggerClass object inside UnitySampleUse we would have to reference and we don't want to make ou app depent upon MyLogger (plus we would have circular reference).

So who's going to glue things together and pass a ILogger object to UnitySampleUse?
Guess what... Unity!

The client of our code, in this case the test project (it could be a UI project or another library), uses Unity to instantiate ILogger, automagically composing our MainClass, passing in the constructor the concrete object implementing ILogger.
The mapping of the interface to the class implementing it can be stored in the xml config file (app.config), that, in our case, will look like this:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration, Version=1.2.0.0,Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
</configSections>

<unity>
<typeAliases>
<!-- Lifetime manager types should be inserted if you need lifetime managers -->
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity"/>
<typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager,Microsoft.Practices.Unity"/>
<!-- User defined type aliases -->
<typeAlias alias="ILogger" type="UnitySampleUse.ILogger,UnitySampleUse"/>
</typeAliases>
<containers>
<container>
<types>
<type type="ILogger" mapTo="MyLogger.MyLoggerClass, MyLogger">
</type>
</types>
</container>
</containers>
</unity>

</configuration>


The test will need to instantiate the MainClass using Unity:


UnityContainer container = new UnityContainer();
UnityConfigurationSection section =
(UnityConfigurationSection)ConfigurationManager.GetSection("unity");

section.Containers.Default.Configure(container);

MainClass mainClass= container.Resolve<MainClass>();


Unity will take care of calling the constructor MainClass(ILogger logger), injecting a MyLoggerClass object. Thus the type of dependency injection applied is constructor injection.

UnitySampleUse project can be compiled without having the source code of the logger and the client code (the unit test, or the ui etc) can switch logger implementation without change in the code by just referencing the new logger and updating the config file.

This way we can separate layers, for example our data access layer, very easily and at the same time keep all our application logic in one project.

Separating layers and building by components has never been easier.

This post is published on

Wednesday, March 25, 2009

Prototyping with Pencil and Powerpoint

I found myself in the need to produce functional specifications for a module of a web application. The requirement was to build some fake screen shots to give the client a representation of how the software will look like.

In past projects I tried paper prototyping, with mixed results and visio diagrams.

This time I looked around to see if some other tool was available and I found Pencil. It's a Firefox 3 plugin that uses the Mozilla Gecko engine. I should say I was really delighted by the simplicity of the tool and the power it gives in building prototypes/wireframes. I was able to be productive in minutes and the results were really good.

You can draw UI shapes, align and resize them with ease and organize them in pages. Then you can batch export those pages as PNG images in a folder. All with just a few clicks.

After doing this I built some detailed spec about how those pages interacted one with each other in a Word document. I was putting every single atomic user interaction down, in numbered points, using the point numbers as anchor reference between points.
As I was doing this I thought it would be more effective if I could just make this really interactive. So it came to my mind I could simply use PowerPoint to achieve this.

It turned out as simple as this:
- I used a print screen of the web app that is going to host the new module, cleaned the body with Gimp and keep just the background color and header and footer.
- Put this image as the background for the PowerPoint slides.
- Insert each PNG image obtained from Pencil in single slides.
- Draw a transparent rectangle (no fill, you can make them transparent by default) on the areas where you want to enable the user to click, for example on a button of a Pencil generated png image.
- On this rectangle, right mouse click and choose "Action settings".
- On the "Action settings" pane you can choose the "Hyperlink to:" option and define the slide to send to upon clicking the rectangle. On the Mouse over tab check the Highligh mouse over option.
- You can also disable clicks on the slide to take viewer on the next slide by selecting 'Slideshow' menu, 'Slide transition' and then uncheck the option that says 'Advance on mouse click'. You can also add a smooth transition and apply on all slides,

This method is really basic and simple, but the results can be quite realistic.

Tuesday, February 10, 2009

Dependency Injection by configuration

In an effort to get better at applying the Dependency Injection pattern in my "framework" for data access separation I looked at a way to move out of the code the reference to the assembly and classes that implement the data session interfaces.

You can read my article at CodeProject to get the details about the interfaces I use to define data access services. In short, I have a ISession interface that is both an Abstract Factory and a Facade to methods that persist and retrieve objects.

The pattern is similar to the Service locator pattern as defined by Martin Fowler.

The data access assembly contains classes that implement the ISession interface and the interfaces for data access for the single entities. Instead of referencing this dll directly in my application model assemblies the file location is specified in the app.config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DALDllFilePath"
value="C:\PathToTheDalDll\Dal.dll"/>
</appSettings>
</configuration>

Then reflection can be used to load the assembly and instantiate the ISession concrete implementation without adding a reference to the assembly containing it. This approach, though, can be expensive in terms of performance, since instantiating object and calling methods through reflection can be substantially slower then doing it directly in code.

We can get around performance issues by performing reflection just once by using a singleton object. Doing reflection just in the static constructor ensures that it is done only once at the first reference to the singleton.

We also need a static method that returns an object implementing the ISession interface.

So we need to initialize and store in the singleton an instance of a factory object implementing the interface shown below.

public interface ISessionFactory
{
ISession GetSession();
}

Having an object implementing this interface in the singleton instance enables us to define a static method that executes GetSession() and returns the ISession concrete implementation to the caller.

The static constructor will load the assembly located at the path retrieved from the config file, search for a class implementing ISessionFactory, instantiating it and storing it in a private field (sessionFactory). The code will be something like:
  
internal class sessionDI
{
private static readonly sessionDI instance = new sessionDI();
ISessionFactory sessionFactory;

static sessionDI()
{
}

private sessionDI()
{
Assembly dalSessionAssembly = Assembly.LoadFile(
System.Configuration.ConfigurationSettings.AppSettings
["DALDllFilePath"]);

Type[] allTypes = dalSessionAssembly.GetTypes();

foreach (Type type in allTypes)
{
if (type.IsClass && !type.IsAbstract)
{
Type iSessionImplementer
= type.GetInterface("ISessionFactory");
if (iSessionImplementer != null)
{
this.sessionFactory =
dalSessionAssembly.CreateInstance(type.FullName)
as ISessionFactory;
}
}
}
if (this.sessionFactory == null)
throw new ApplicationException("Configuration error");
}

internal static ISession GetSession()
{
return instance.sessionFactory.GetSession();
}
}


The GetSession() singleton static method will simply call the GetSession() method of the sessionFactory object singleton instance loaded at singleton construction.

Tuesday, January 6, 2009

Building an Agile SQL Data Access Layer

Following my previous article on separating application layers and using an In-memory persistence to "fake" the real data access layer, I've published a new article on implementing the actual data access using the previously outlined architecture and ado.net.

The article is: Building an Agile SQL Data Access Layer.

Friday, November 21, 2008

In memory data access, a methodology to simplify agile development.

[This post is now a CodeProject article]

Object oriented design concepts and agile development principles state that data access is a detail and not part of the domain of the application model. This means that the architecture of applications should ensure that the implementation of object persistence and retrieval is hidden from the domain of the application model.

With the complete decoupling of the data access layer comes the possibility to test the business model in isolation by providing a data access layer that mimics a real one but doesn't carry the entire heavy infrastructure needed by a RDBMS and the code to access it.

A possible way to simulate a data access layer is to use mock objects. This blog post proposes a slightly different approach that consists of implementing a simple "In memory" data access and persistence mechanism.

This approach allows deferring the development of the database details, typically involving implementing table structures, sql generation scripts, sql queries and other configurations.

But how do we obtain complete separation of the data access layer?

Dependency Inversion

The Dependency Inversion Principle, as Robert C. Martin stated in "Agile Principles, Patterns and Practices in C#" says that:
  • High level modules should not depend upon low level modules. Both should depend upon abstractions.

  • Abstractions should not depend upon details. Details should depend upon abstractions.
Dependency inversion separates concerns and enables a top-down developing process, building high level modules before low level modules.

.NET implementation

Applied to the .net world, dependency inversion implies that:
  • The DAL (data access layer) should be in a separate assembly.

  • The business logic layer and the DAL should depend upon common interfaces defined in a third assembly.

  • The DAL shouldn't have the responsibility of instantiating objects, the business logic layer should.
This diagram shows the architecture of this solution for layer separation.



We have 4 assemblies:

  • Entities: holds definition for the entities in the application model. It doesn't reference any of the other assemblies.

  • Logic: contains the application business rules (object creation included). It references Entities and Interfaces.

  • Interfaces: contains contracts for low level modules. Data access, in our case. It references Entities.

  • Data Access: provides services for persisting and retrieving objects. It references Entities and Interfaces.
To look at some code I'll use an example application about business order management.

Entities

Here is the class diagram that represents the entities:



Interfaces

The separation we are looking for can be obtained by applying abstract factory and facade patterns through the definition of a group of interfaces, one for each entity class, wrapped together by an interface adding connection and transaction management. As in the following class diagram.



The IOrdersSession interface will orchestrate data access functionality provided by all the single entity data access classes.

public interface IOrdersSession: IDisposable
{
IDbTransaction BeginTransaction();

ICustomerDAL DbCustomer { get; }
void Save(Customer customer);
void Delete(Customer customer);

IOrderDAL DbOrder { get; }
void Save(Order order);
void Delete(Order order);

IOrderItemDAL DbOrderItem { get; }
void Save(OrderItem orderItem);
void Delete(OrderItem orderItem);

IProductDAL DbProduct { get; }
void Save(Product product);
void Delete(Product product);
}

This interface derives from IDisposable to ensure that any database connection is closed (and transaction rolled back if still present) at object disposal and to enable the use of the using statement.

This is the code for the Order entity data access interface:

/// method to call to instantiate objects
public delegate Order OrderDataAdapterHandler(
Guid id, Guid idCustomer, DateTime orderDate);

/// <summary>
/// Order data access interface
/// </summary>
public interface IOrderDAL
{
List<Order> Search(Guid id, Guid idCustomer,
DateTime? orderDate,
OrderDataAdapterHandler orderDataAdapter);
}
A callback mechanism is used to instantiate objects off the data access layer. A delegate, OrderDataAdapterHandler, is passed as a parameter in the methods that retrieve objects (the search method in our example). A blog post by Scott Stewart is available for detail info about this alternative to using DTOs to retrieve data from the DAL.

Logic

The business logic classes shouldn't have a direct reference to the DAL classes. Instead, they will reference the IOrdersSession interface and a Dependency injection (DI) mechanism will provide the actual object implementing it.

Dependency injection can be provided by a DI framework (such as NInject or Unity) or, as in the sample code here quoted, by a simple method that instantiates an object implementing IOrdersSession. In this case this is done in a conditional way: business logic classes decorated with the [InMemoryDAL] attribute will be injected with the InMemory access classes.

public class InMemoryDALAttribute : System.Attribute { }

public class GBDipendencyInjection
{
public static IOrderdSession GetSession()
{
// get call stack
StackTrace stackTrace = new StackTrace();

// get calling class type
Type tipo = stackTrace.GetFrame(1).GetMethod().DeclaringType;

object[] attributes;

attributes = tipo.GetCustomAttributes(
typeof(InMemoryDALAttribute), false);

if (attributes.Length == 1)
{
return new InMemoryOrderSession();
}
else
{
return new SqlServerOrderSession();
}
}
}
Methods that need to retrieve data will instantiate IOrderSession in a using statement and pass as a parameter a factory method with a signature corresponding to the one defined in the entity DAL interface.
public List<Order> GetByCustomerId(Guid customerId)
{
List<Order> lis;
using (IOrdersSession sess
= GBDipendencyInjection.GetSession())
{
lis = sess.DbOrders.Search(Guid.Empty, customerId, null,
CreateOrder);
}
return lis;
}
In the OrderLogic class, CreateOrder is the factory method that instantiates objects of type Order.

public Order CreateOrder(Guid id,
Guid idCustomer,
DateTime orderDate)
{
Order order = new Order();
CustomerLogic costumerLogic = new CustomerLogic();
Customer customer = costumerLogic.GetById(idCustomer);
if (customer == null)
{
throw new ArgumentException("Customer not found.");
}
order.Customer = customer;
order.OrderDate = orderDate;
return order;
}

In Memory Data Access

A singleton class contains a generic list of the objects whose storage is simulated. Since it is a singleton, it maintains the list across threads, thus it can be still used when developing the interface (even a web interface) and defer database development in the last stages of development. Cascading Find method is applied to search the list.
public sealed class OrderInMemoryDAL : IOrderDAL
{
internal List<Order> OrderList;

static readonly OrderInMemoryDAL _istance
= new OrderInMemoryDAL();

private OrderInMemoryDAL()
{
OrderList = new List<Order>();
}

internal static OrderInMemoryDAL Istance
{
get { return _istance; }
}

#region IOrderDAL Members

public List<Order> Search(Guid id, Guid idCustomer,
DateTime? orderDate, OrderDataAdapterHandler orderDataAdapter)
{
List<Order> lis = OrderList;

if (id != Guid.Empty)
{ lis = lis.FindAll(
delegate(Order entity) {
return entity.Id == id; });
}
if (idCustomer != Guid.Empty)
{ lis = lis.FindAll(
delegate(Order entity) {
return entity.Costumer.Id == idCustomer; });
}
if (orderDate.HasValue)
{ lis = lis.FindAll(
delegate(Order entity) {
return entity.OrderDate == orderDate; });
}

return lis;
}

#endregion
}
InMemoryOrderSession implements IOrdersSession managing saving and deleting simply by adding and removing from the generic lists stored in the singleton objects.

public class InMemoryOrderSession: IOrdersSession
{
...
public IOrderDAL DbOrders
{
get { return OrderInMemoryDAL.Istance; }
}

public void Save(Order order)
{
Delete(order);
OrderInMemoryDAL.Istance.OrderList.Add(order);
}

public void Delete(Order order)
{
OrderInMemoryDAL.Istance.OrderList.RemoveAll(
delegate(Order _entity)
{ return _entity.Id == order.Id; }
);
}

...
}

This approach enables to develop the model and even the user interface without worrying about the database details. This lowers the cost of changes to the model since it is not required to change database structures and sql scripts and queries.

Another advantage is being able to test the business logic in isolation from the database access code.

The last stage of the development of our application will be writing a class implementing IOrdersSession that makes use of a RDBMS through an access library, like ADO.NET, providing connection and transaction services.This class will be a facade for all the single classes that manage CRUD operations on the RDBMS for model entities persistence.

The next step will be removing the [InMemoryDAL] attribute from the business logic class. Now the simple DI mechanism will inject the "real" DAL in the application. Running unit tests on the business logic classes again, the DAL will be tested.

If you're interested to see the sample application you can download the file containing the complete Visual Studio solution.

In next posts I'll focus on the developing of these classes, extending the current sample code and on the CodeSmith templates that can generate much of the glue code necessary for implementing this architecture.

Delicious
Bookmark this on Delicious

kick it on DotNetKicks.com

Thursday, November 20, 2008

Follow the Yellow Brick Road



Follow the yellow brick road, follow the yellow brick road
Follow, folllow, follow, follow, follow the yellow-brick road
Follow the yellow-brick, follow the yellow-brick
Follow the yellow-brick road

You're off to see the Wizard, the Wonderful Wizard of Oz
You'll find he is a Whiz of a Wiz if ever a Wiz there was
If ever, oh ever, a Wiz there was the Wizard of Oz is one because
Because, because, because, because, because
Because of the wonderful things he does
You're off the see the wizard, the Wonderful Wizard of Oz

... Just to explain the blog title ...