Friday, September 10, 2010

The 5 minute Dependency Injection Container

In order to decouple dependent components you have to make sure that the consumer component that depends on a service component doesn't need to create the service component.
This pattern is called Dependency Injection (Martin Fowler).

There are many DI frameworks available: Ninject, Spring.NET, Structuremap, Unity Application Block (Unity), Managed Extensibility Framework (MEF). It's not worth to worry about creating your own. However if you build a simple app and you need something light and simple, or if you just want to understand the concept of DI without the overhead of having to learn an API then you can use the following simple container to do some DI. The LightContainer has many limitations: supports only singletons, doesn't support named instances and doesn't inject dependencies automatically using typically reflection like the "good" libraries do. On the other hand it's simple to understand and thus it's easy to extend. In addition it's very fast since reflection is not necessary.

How to use it

Assume we have the following view-viewmodel and we'd like to wire them up using Dependency Injection. The first thing we need is an instance of the container. Then we need to register the lambdas that can create our services. Note that the sequence of the registration is not important. Now when we need an service instance, say a View, we simply resolve it from the container.

0 comments:

Post a Comment

Post a comment