StructureMap is a dependency injection framework.Dependency Injection is a set of software design principles and patterns that enable us to develop loosely coupled code. It’s primary goal is to help us to reduce the mechanical costs of good object oriented design. Also it’s very helpful for testing purpose.
Dependency injection is the best thing to do when you have some blocks having multiple implementations and you have to decide which implementation to use.Recently i used dependency injection in a ASP.NET based web application.

Using StructureMap with C#

To use StructureMap in your project you only need Structuremap.dll file which you can download from it’s website. After that add a reference to this file in your project. Let’s see a demo of this.
Open Visual Studio and create a C# based console application. Now in solution explorer pane right click on reference node and select Add reference. Add reference to structuremap.dll file. Now add a xml file in your project and put this code in it:

<?xml version="1.0" encoding="utf-8" ?>
<StructureMap>
 <Assembly Name="InterfaceConsole" />
</StructureMap>

Now add one more class to the project and name it IDemo.cs. This is a interface. Code:

using StructureMap;
namespace InterfaceConsole
{
 [PluginFamily("Mykey")]
 public interface IDemo
 {
 string Hello();
 }
}

Now add a new class to the project and name it Hello.cs. Here we’ll implement Code:

using StructureMap;
namespace InterfaceConsole
{
[Pluggable("Mykey")]
public class Hello: IDemo
{
public string Hello()
{
return "Hello! This is from Hello Class.";
}
}
}

Now come to your program file and enter this code:

using System;
using StructureMap;
namespace InterfaceConsole
{
 class Program
 {
 static void Main(string[] args)
 {
 IDemo dmo = ObjectFactory.GetInstance<IDemo>();
 Console.WriteLine(dmo.Hello());
 Console.ReadLine();
 }
 }
}

When you run this program you will get “Hello! This is from Hello class.”. You can get same output by making the object the of Hello class and after that assigning that object to IDemo class object ( off-cource you need to type cast Hello object in that situation). But here structuremap makes it eaiser.
However, Using Dependency injection in small projects is not a good idea.