Ryan Lanciaux

Random programming blog.

Very Quick and Simple Dependency Injection With StructureMap

There are a lot of resources on the web about dependency injection and using StructureMap, however, I wanted to write something that was an extremely simple example. This is basically the tip of the iceberg but hopefully it will help someone. 

We want to make our application very loosely coupled – to achieve this 'loose coupling' we're going to have several projects in the solution. What this means if we need to change any part of this application later on (we wouldn't want to in this case since its a demo and all), we could do so without impacting everything else. Anyways, we're going to create three class libraries and a WinForms application.

Next we want to create our main inteface – this will be under the DisplayMessage Project:

 

namespace DisplayMessage

{

    public interface IDisplayMessage

    {

        string message();

    }

}

The interface defines just one method that, when implemented, will return a string stating what class its coming from. Next, we want to create our two implementation classes (one under Implementation1, the other under Implementation2). Please keep in mind I'm not suggesting to have every class in it's own library – it's just for the sake of example :)

Implementation1:

    public class MessageOne : IDisplayMessage

    {

        public string message()

        {

            return "This is a message from Implementation1";

        }

    }

 Implementation2:

    public class MessageTwo : IDisplayMessage

    {

        public string message()

        {

            return "This is a message from Implementation2";

        }

    }

Okay that was easy enough, now on to the Forms App.  We're first going to add a reference to StructureMap and the project DisplayMessage and create a file called StructureMap.config – this config file is going to define all of our assemblies. We want to make sure we edit the properties of this file and set the Copy to Output Directory option to "Copy Always." StructureMap will use this file at runtime to get our object references. The config file looks like this: 

<?xml version="1.0" encoding="utf-8" ?>

<StructureMap>

  <Assembly Name="DisplayMessage" />

  <Assembly Name="Implementation1" />

  <Assembly Name="Implementation2" />

 

  <PluginFamily Type="DisplayMessage.IDisplayMessage"

                Assembly="DisplayMessage"

                DefaultKey="MessageOne">

    <Plugin Type="Implementation1.MessageOne"

            Assembly="Implementation1"         

            ConcreteKey="MessageOne" />

    <Plugin Type="Implementation2.MessageTwo"

                Assembly="Implementation2"

                ConcreteKey="MessageTwo" />   

  </PluginFamily>

</StructureMap>

Notice we define a PluginFamily for the IDisplayMessage interface and set the default implementation to be MessageOne (the DefaultKey of PluginFamily references the ConcreteKey of the Plugin). Other than that, this should be pretty straight-forward but if you have any confusion, please check out the StructureMap documentation. Only a couple more things to do before we can run this…

Ok, we're going to add 3 buttons to our form – one for the default IDisplayMessage and one for each implementation.

 Now to add the code…

        //Default IDisplayMessage 

        private void btnDefault_Click(object sender, EventArgs e)

        {

            IDisplayMessage msg = StructureMap.ObjectFactory.GetInstance<IDisplayMessage>();

            System.Windows.Forms.MessageBox.Show(msg.message());

        }

 

        //Implementation1

        private void btnOne_Click(object sender, EventArgs e)

        {

            IDisplayMessage msg = StructureMap.ObjectFactory.GetNamedInstance<IDisplayMessage>("MessageOne");

            System.Windows.Forms.MessageBox.Show(msg.message());

        }

 

        //Implementation2

        private void btnTwo_Click(object sender, EventArgs e)

        {

            IDisplayMessage msg = StructureMap.ObjectFactory.GetNamedInstance<IDisplayMessage>("MessageTwo");

            System.Windows.Forms.MessageBox.Show(msg.message());

        } 

Lets parse this up a little bit…

  • IDisplayMessage msg = StructureMap.ObjectFactory.GetInstance<IDisplayMessage>();

    This statement gets the default IDisplayMessage object in the StructureMap.config file. Currently, it will get the same object as getting a named instance of "MessageOne"
  • IDisplayMessage msg = StructureMap.ObjectFactory.GetNamedInstance<IDisplayMessage>("MessageOne");

    This statement gets the object associated with the ConcreteKey "MessageOne"
  • IDisplayMessage msg = StructureMap.ObjectFactory.GetNamedInstance<IDisplayMessage>("MessageTwo");

    This statement gets the object associated with the ConcreteKey "MessageTwo"

Instead of simply hitting F5, we will need to build the application – we want to copy the DLL files from Implementation1 and Implementation2 to the bin directory of the forms app and run the executable there.  For testing, however, we can add a reference to both projects (this completely defeats the purpose of dependency injection so be sure to remove the references later on) or adjust the output directory of the implementation class libraries to be the same as the Form application's bin directory. Running the application shows that everything is working as expected.

For more information please check out the following links: