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.