Archive for the ‘ASP.NET’ Category

Dependency injection with Spring.NET

Hands-on introduction on how to configure dependency injection using Spring.NET

In a previous post I’ve discussed a simple n-tier approach using a Facade and Dao pattern. The Facade provides a single access point for the business tier, and wraps a data access object that encapsulates the implementation of the persistence mechanism, separating the concerns.

I also mentioned that these objects introduce a large dependency (high coupling) as the Facade does not function without the Dao. I will now show you how this dependency can be overcome, by injecting the Dao into the Facade using the Spring.NET framework.

In the following example we will create a simple web management tool for a Zoo (inspired by amazedsaint). The tool needs to list all animals and caretakers, and allow the manager to rename animals or to assign one or more caretakers to an animal.

We start out by creating the business entities:


public class Caretaker

{

public string Name { get; set; }

public int Age { get; set; }

}

public abstract class Animal

{

public string Name { get; set; }

public IList<Caretaker> Caretakers { get; set; }

}

public class Lion : Animal { }

public class Elephant : Animal { }

We will also create a Facade which allows consumers to have a good understanding of the class library without having to worry about the exact implementation. Therefore, a good practice is to set up an interface:


public interface IZooManagement

{

IList<Animal> GetAllAnimals();

IList<Caretaker> GetAllCaretakers();

void RenameAnimal(Animal a, string newName);

void AssignCaretaker(Animal a, Caretaker c);

}

This should cover all requirements. The animals and caretakers will be stored in some kind of data store, so we’ll create a data access object (Dao) that will handle this for us. We haven’t decided on which type of data store or which ORM to use, so for now, let’s not worry about its implementation and create the interface:


public interface IZooDao

{

IList<Animal> GetAllAnimals();

IList<Caretaker> GetAllCaretakers();

void UpdateAnimal(Animal a);

}

Ok, now let’s implement the Facade. For the sake of simplicity, I will leave out any validation or error handling. Eventually, the minimal implementation will look much like this:


public class ZooManagement : IZooManagement

{

private IZooDao dao;

public virtual IZooDao Dao

{

set { dao = value; }

}

public IList<Caretaker> GetAllCaretakers()

{

return dao.GetAllCaretakers();

}

public IList<Animal> GetAllAnimals()

{

return dao.GetAllAnimals();

}

public void RenameAnimal(Animal a, string newName)

{

a.Name = newName;

dao.UpdateAnimal(a);

}

public void AssignCaretaker(Animal a, Caretaker c)

{

a.Caretakers.Add(c);

dao.UpdateAnimal(a);

}

}

The persistence mechanism has now completely been abstracted from the Facade. Also notice that the Facade does not instantiate a Dao: the property allows us to “inject” the Dao implementation and completely remove the dependency (this can also be done using a constructor parameter).

We now need to find a good way to inject the Dao into the Facade, and this is where the Spring.NET framework provides additional support, as one of its many features allows you to set up dependency injection through configuration.

Before we configure the dependency injection, let us create a “dummy” Dao, one that does not really access a data store, but holds a list of animals and caretakers internally:


public class DummyDao : IZooDao

{

private IList<Animal> animals;

private IList<Caretaker> caretakers;

public DummyDao()

{

animals = new List<Animal>();

animals.Add(new Lion() { Name = "Simba" });

caretakers = new List<Caretaker>();

caretakers.Add(new Caretaker() { Name = "Leo", Age = 25 });

}

public IList<Animal> GetAllAnimals()

{

return animals;

}

public IList<Caretaker> GetAllCaretakers()

{

return caretakers;

}

public void UpdateAnimal(Animal a)

{

throw new NotImplementedException();

}

}

If you want to use the Spring.NET framework, you will first need to add a reference to your web project. The latest version can be downloaded here. Next, you’ll need to configure Spring.NET in the Web.config:


<sectionGroup name="spring">

<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>

<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>

<sectionGroup name="child">

<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>

</sectionGroup>

</sectionGroup>

<spring>

<context name="ParentContext">

<resource uri="config://spring/objects"/>

</context>

<objects xmlns="http://www.springframework.net">

<object id="ZooDao" name="ZooDao" type="TheseDays.Business.DAL.DummyDao, TheseDays.Business">

</object>

<object id="ZooManagement" name="ZooManagement" type="TheseDays.Business.ZooManagement, TheseDays.Business">

<property name="Dao">

<ref local="ZooDao"/>

</property>

</object>

</objects>

</spring>

The first part is standard and announces the Spring.NET configuration. The second part is where the magic happens: the spring/context section is necessary for Spring to create its application context, and the spring/objects section allows you to configure the resources.

The object configuration is pretty straightforward: we tell Spring.NET we want to create an object of type ZooManagement (our Facade) and to set its property with an object we also configured, an object of type DummyDao.

Once we have implemented an actual Dao (rather than a dummy one), in order to start using it all we need to do is reconfigure its type. For example, if we would create a RealDao that also implements the IZooDao interface, and we need to pass a connection string to the constructor, the configuration of the Dao would look like this:


<object id="Dao" name="Dao" type="TheseDays.Business.DAL.RealDao, TheseDays.Business">

<constructor-arg name="connectionString">

<value>Server=.;Initial Catalog=Zoo;User=ZooUsr;Password=ZooPwd;Application</value>

</constructor-arg>

</object>

In the web application we can then access the ZooManagement Facade through the Spring’s application context. Here’s a demonstration of a small helper class I often use:


public class ApplicationContextHolder

{

private static ApplicationContextHolder instance = new ApplicationContextHolder();

public static ApplicationContextHolder Instance

{

get { return instance; }

}

private IApplicationContext applicationContext;

private IZooManagement zoo;

private ApplicationContextHolder()

{

applicationContext = ConfigurationManager.GetSection("spring/context") as IApplicationContext;

zoo = applicationContext.GetObject("ZooManagement", typeof(ZooManagement)) as IZooManagement;

}

public IApplicationContext ApplicationContext

{

get { return applicationContext; }

}

public IZooManagement Zoo

{

get { return zoo; }

}

}

Now you can access the ZooManagement in the web pages with a single line of code:


IZooManagement zoo = (ZooManagement)ApplicationContextHolder.Instance.Zoo;

Surely a nice feature when you’re building your own framework!

You can download the full source code of the example here.