In my previous post, Inverting my control, I talked about the Inversion of Control (IoC) pattern. Since that time, I have received a number of requests for a full set of source code so people can review or steal my implementation of this pattern. If you are new to this pattern this can serve as a simple introduction leading to you using one of the more advanced open source tools or building something yourself. Keep in mind this is a very simple implementation to facilitate learning and to=o help enable IoC approaches for small projects that just don't need the bigger toolkits.
Implementing this is pretty easy... Here is a quick walk-through:
1. Download the source code (SmellyContainer.zip (12.50 kb)) and compile the solution
2. In the consuming application, add a reference to "Smelser.Container.dll"
3. In the consuming application config file, register the configuration section for the container
<configSections>
<section name="smelser.container" type="Smelser.Container.Configuration.ContainerConfigSection, Smelser.Container" />
</configSections>
<smelser.container>
<components resolver="Smelser.Container.DependencyResolver, Smelser.Container">
</components>
</smelser.container>
4. Register concrete implementations
<smelser.container>
<components resolver="Smelser.Container.DependencyResolver, Smelser.Container">
<component contract="Sample.IFoo, Sample" implementation="Sample.Foo, Sample" />
</components>
</smelser.container>
5. Import the namespace into the consuming class file
using Smelser.Container;
6. Resolve types using static IoC container methods.
IFoo theFoo = IoC.Resolve<IFoo>();
theFoo.Name = "My Foo";
Console.WriteLine("Successfully constructed an instance of IFoo with the Name '{0}'", theFoo.Name);
This can also be used in overloaded constructor to facilitate injection off default types and mocked types for testing.
public Sample()
: this(IoC.Resolve<IFoo>())
{
...
}
internal Sample(IFoo foo)
{
...
}
Thats it... Yes... it is that simple...