Inversion of Control with Spring.NET

posted @ Tuesday, April 11, 2006 7:48 AM

 

I have previously mentioned using the Spring Framework for the AOP support the framework provides, however Spring is deeply rooted in providing dependency injection or Inversion of Control (IoC). Spring uses a configuration file to manage type relationship mappings to objects, which can be stored in its own external XML file, an embedded resource within an assembly, or directly within your web.config or app.config file. For a simple example, we will define our own XML file (spring.xml), with the following contents:

 

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<object name="Database"
singleton
="false"
type
="SpringDemo.Database, SpringDemo">
<constructor-arg ref="SqlConnectionObject" />
<
constructor-arg ref="SqlCommandObject" />
</
object>
<object name="SqlConnectionObject"
singleton
="false"
type
="System.Data.SqlClient.SqlConnection, System.Data">
<constructor-arg type="System.String"
value
="Data Source=demo;Initial Catalog=pubs;User Id=sa;Password=pwd;" />
</
object>
<object name="SqlCommandObject"
singleton
="false"
type
="System.Data.SqlClient.SqlCommand, System.Data">
</object>
</objects>

With this example we define three objects; a Database, a SqlConnection and a SqlCommand. From this, we can provide Spring with our resource file and create an XmlObjectFactory that will allow our application to request services from it.

 

using System;
using
Spring.Core.IO;
using
Spring.Context;
using
Spring.Context.Support;
using
Spring.Objects.Factory;
using
Spring.Objects.Factory.Xml;

namespace
SpringDemo
{
class Program
{
static void Main(string[] args)
{
IResource resource
= new FileSystemResource("spring.xml");
IObjectFactory factory = new XmlObjectFactory(resource);
if
(factory != null)
{
IDatabase db
= factory.GetObject("Database") as IDatabase;
if
(db != null)
{
if (db.Connection != null)
{
Console.WriteLine(db.Connection.ConnectionString)
;
}
}
}
Console.WriteLine(
"Done");
Console.Read();
}
}
}

Note that when the "Database" is requested from our XmlObjectFactory, Spring identifies that it has two dependent objects, a SqlConnection and a SqlCommand object which need to be constructed prior to creating the "Database" object. In fact, the Database class has a constructor that takes an IDbConnection and IDbCommand. When the SqlConnection object is created, it uses the overloaded constructor to pass in a connection string which was defined as a constructor argument when the SqlConnection was created. Thus all dependent objects are created and passed into the Database object. Source code can be downloaded here.