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" ?>
<constructor-arg ref="SqlConnectionObject" />
<constructor-arg ref="SqlCommandObject" />
value="Data Source=demo;Initial Catalog=pubs;User Id=sa;Password=pwd;" />
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.
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)
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.