Notes on Spring.NET DAO Code Configuration

In this short article, we will look at how Dependency Injection for Data Access Objects can be implemented using Spring.NET.

“Data Access support in Spring is aimed at making it easy to work with data access technologies like ADO.NET and Nhibernate in a standardized way.”- Spring.NET

First an interface that exposes the methods that can act on a database.


public interface IShapeDao
{
   DataTable GetShape();
}

Then some implementations for this interface.


// Implementation 1
public class CircleDao: AdoDaoSupport, IShapeDao
{
   public DataTable GetShape()
   {
       var sql = " Select * from tblCircle";
       return AdoTemplate.DataTableCreate(CommandType.Text, sql);
   }
}

// Implementation 2
public class RectangleDao: AdoDaoSupport, IShapeDao
{
   public DataTable GetShape()
   {
       var sql = " Select * from tblRectangle";
       return AdoTemplate.DataTableCreate(CommandType.Text, sql);
   }
}

Notice that no connection strings or database context are provided here.

Now, the Configuration class. Each dependent object will have its own virtual method as below:


[Configuration]

public class MyConfiguration: IApplicationContextAware
{
    public IApplicationContext ApplicationContext { get; set; }

   [Definition(Names="circle"]
   [Lazy]
   [Scope(ObjectScope.Singleton)]
   public virtual IShapeDao CircleDao()
   {
      return new CircleDao();
   }

   [Definition(Names="rectangle"]
   [Lazy]
   [Scope(ObjectScope.Singleton)]
   public virtual IShapeDao RectangleDao()
   {
      return new RectangleDao();
   }
}

Next, all we need to do is initialize the ApplicationContext by passing the required dependency.In the program main process i.e. where the app begins and all the action starts, we initialize the ApplicationContext.


private IApplicationContext context;

public void InitContext()
{
   // Configure Spring programmatically
   var ctx = new CodeConfigApplicationContext();
   ctx.ScanWithAssemblyFilter(a => a.FullName.StartsWith("My.Assemble.Name.Path"));
   ctx.Refresh();
   context = ctx;
}

Finally, we can ask for our object from this context like this:


IShapeDao circleDao = context.GetObject<IShapeDao>("circle");
IShapeDao rectangleDao = context.GetObject<IShapeDao>("rectangle");

This is pretty much all the needed fundamentals for using Spring.NET DAO.

Happy Programming!

Tags: