StructureMap 2.5
For the past week, I’ve been trying out StructureMap, a dependency injection framework for .NET. I’ve tried a few DI/IoC containers before including Spring and Castle Windsor and I feel right at home with StructureMap.Usually when I try out a new framework, I usually look at how much time it takes and how much code I have to write to get some basic (HelloWorld) program running. Comparing to Spring, I found StructureMap API and configuration more intuitive and efficient. Here are the example
public interface IHelloWorld { void SayHello(); } public class JapaneseHelloWorld: IHelloWorld { public string Name { get; set; } public void SayHello() { Console.WriteLine("Konijiwa! " + Name); } } public class SpanishHelloWorld: IHelloWorld { public string Name { get; set; } public void SayHello() { Console.WriteLine("Ohla! " + Name); } }
Here I have a hello world interface with 2 speaker classes, Japanese and Chinese. In my client project, I add a new file called StructureMap.config with the following configuration.
In my client program, I run the following code
IList<IHelloWorld> helloWorlders = ObjectFactory.GetAllInstances<IHelloWorld>(); //return list of 2 IHelloWorld jap = ObjectFactory.GetNamedInstance<IHelloworld>("Japanese"); jap.SayHello();
The output is “Konijiwa! Koizumi-san”. As you can see, the amount of code I have to write and configuration files are quite minimum. Less code is always a good code. I also found StructureMap API to be well thought out and straight to the point of getting things done. Definitely worth your time checking it out.
Teera on November 14th 2008 in Software Development, .NET