Sep 30 2007

Really Simple Dependency Injection

Published by at 7:47 pm under .NET,Programming

Having just started a new job I find it interesting to see the way that the other developers I’m working with do things. One of the things I found in the code was for doing dependency injection. I’m not going to analyse that code as but what I will say is that I managed to replace 10 lines of code with just 3.

Without further ado here is the C# code:

public static T Get<T>() where T : class
{
string implName = Program.Settings[typeof(T).Name].ToString();
object concrete = Activator.CreateInstance(Type.GetType(implName));
return (T)concrete;
}

So what can you do with this code? Well, the way it is written means that you can create an object, the class of which is defined in a configuration file. This allows you to program to an interface but decide the concrete class in the configuration file. The method above will find the class defined for the interface being passed in, create an object of that type and return the object cast to the type of the interface.

The code used to call the method:
IPlugin plugin = PluginFactory.Get<IPlugin>();

plugin.OutputMessage("hello, world!");

The definition in the config file:
<setting name="IPlugin" serializeAs="String">
<value>GrinGod.Dependency.PluginTwo.PluginTwo,GrinGod.Dependency.PluginTwo</value
</setting>

I’m sure I haven’t explained terribly well, so I’ve thrown together a simple example that you can download. I should point out that this code a very simple example of dependency injection, it doesn’t handle passing values to the constructor of the object being instantiated, although it would be simple to add that. Also, the example I have included statically links to the two plugin assemblies, this could be changed such that the plugin assemblies are dynamically loaded using Assembly.Load()

If you want a more fully featured implementation of dependency injection you should check out the Spring.Net framework.
kick it on DotNetKicks.com

Technorati Tags: , , ,

3 responses so far

3 Responses to “Really Simple Dependency Injection”

  1. mcgurkon 18 Oct 2007 at 7:00 pm

    Um, what happens when a lowly programmer does Get()?

    I’d suggest:
    public T Get() where T : class
    {…}

    Slick, simple otherwise. It likes. It kicks.

  2. mcgurkon 18 Oct 2007 at 7:01 pm

    Oh dude, that completely sucked. It nuked the angle brackets.

    Lemme try again…

    Get<int>()

  3. gringodon 18 Oct 2007 at 11:32 pm

    Point taken. It’s still not bomb proof, but then I did say that this is a really simple example.

Comments RSS |

Leave a Reply