Sep 30 2007

Really Simple Dependency Injection

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

This is an old article and the information contained within it may be out of date, not reflect my current views and/or contain broken links. If you feel this article is still valid and requires updating, you can use the contact form to let me know. However, I make no guarantee that it will get updated.

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">

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

Technorati Tags: , , ,

3 responses so far