How To: Dependency Injection with Spring.NET

Download the sample Dependency Injection project.

Until recently I hadn’t explored an implementation of Dependency Injection (DI), or Inversion of Control (IoC), but knew I had uses for it.  If you’re interested in the types of Dependency Injection or are looking for a good explanation check out Martin Fowler’s Inversion of Control Containers and the Dependency Injection pattern article.  My interest was in having the ability to write code which implements an interface, having the client work against the interface, and loading the implementation at run time.  The benefit?  I can change my implementation at will without having to recompile and retest the whole app.  If this is sounding familiar you may be comparing it to the Provider pattern commonly used in the .NET framework.

Finally I had a project I felt was a great candidate for the Dependency Injection pattern and did some work with Spring.NET.  Here’s a straightforward example for getting started.

Create a new project called Spring.Net.Test and add an interface called IClass (we’re going real generic here).

IClass.cs
namespace Spring.Net.Test
{
   
public interface IClass
    {
       
string Name { get; }
    }
}

Next  create two classes called ClassA.cs and ClassB.cs and have both implement IClass.

ClassA.cs
namespace
Spring.Net.Test

{

    public class ClassA : IClass

    {

        public string Name

        {

            get { return "Class A"; }

        }

    }

}

 

ClassB.cs
namespace
Spring.Net.Test
{
   
public class ClassB : IClass
    {
       
public string Name
        {
           
get { return "Class B"; }
        }
    }
}

Now I’d want to use Dependency Injection to obtain a class which implements IClass.  We have two of them but the client app shouldn’t care which one is returned… just that it implements IClass.  To make this easily usable let’s create a factory to return an instance of IClass.  I called it IClassFactory.

IClassFactory.cs
using
System.IO;

using Spring.Objects.Factory.Xml;

 

namespace Spring.Net.Test

{

    public class IClassFactory

    {

        public static IClass CreateIClass()

        {

            using (Stream stream = File.OpenRead(@"C:\path to your config file\config.xml"))

            {

                Spring.Core.IO.InputStreamResource resource = new Spring.Core.IO.InputStreamResource(stream, "config");

                XmlObjectFactory xmlObjectFactory = new XmlObjectFactory(resource);

                IClass IClassObj = (IClass) xmlObjectFactory.GetObject("IClassObject");

                return IClassObj;

            }

        }

    }

}

Notice the first thing we’re doing is opening up an XML file which is the configuration file to tell Spring.NET what assembly and class to create an instance of.  Spring.NET then takes the stream in, locates the configuration for “IClassObject” and does some lifting to give us our object.  The configuration is simple. 

Config.xml
<?
xml version="1.0" encoding="utf-8" ?>
<
objects xmlns="http://www.springframework.net">
    <
object name="IClassObject" singleton="false" type="Spring.Net.Test.ClassB,Spring.Net.Test" />
</
objects>

Lastly we’ll write a test with NUnit to verify the functionality. 

Tests.cs
using NUnit.Framework;

 

namespace Spring.Net.Test

{

    [TestFixture]

    public class Tests

    {

        [Test]

        public void FactoryTest()

        {

            IClass myClass = IClassFactory.CreateIClass();

            Assert.AreEqual(myClass.Name, "Class B");

        }

    }

}

That’s pretty much it!  There are other packages than Spring.NET but I’ve yet to check them out.  Have you found another to be better?  How about performance of using DI? 

Download the sample Dependency Injection project.

kick it on DotNetKicks.com
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Related posts

Comments

May 15. 2008 06:29 AM

Arturas

You might want to check our newly released IoC (dependancy injection) container - winter4.net

Arturas

June 13. 2008 08:41 AM

Rogier

I'm trying to figure out the usefulness of Spring, but I can't dig it yet. Mainly because most examples use a very simplified hardcoding variant of a factory. I'm sure it's my fault that I don't understand it, but I really want to understand... I would like to see a real world example.

Suppose ClassA is an Oracle implementation, while ClassB is the SQL-server variant. I have a webpage that uses either Oracle or SQL-server. The webpage implements the interface, and a factory gives me the right implementation. So far so good.

All examples, including yours, end their (very interesting and well written) story with the anti climax: Put the (factory) decision which class you want into a web.config like:
type="Spring.Net.Test.ClassB

That's hardcoding.. while in real life the decision is based on something dynamicFrownat worse) a dropdownbox for instance (Select Oracle or SQL-server). But more often on the outcome of some other logic (like the DAL).

Furthermore, the example implies that I have to create a web.config for each and every webpage (Supposing that I actually do have two webpages: one for Oracle and one for SQL-server), I have to place them in separate folders and add a web.config. And then use a old fashioned factory to get the right webpage?

Could you please help me out with this? Many thanks!

Rogier

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]



Live preview

July 23. 2008 11:26 AM

About Me

I'm Ian Suttle and I work for IGN Entertainment, a division of Fox Interactive Media.

Recent posts