The subject of Dependency Injection (DI) and Inversion of Control (IoC) containers has received a lot of attention over the last few years. Building applications that are loosely coupled has become more and more popular (and for good reason) especially in applications that have a lot of dependencies that could break over time or need to handle the addition of new modules seamlessly. From a personal standpoint I fall somewhere in the middle of the overall DI argument. I definitely feel that DI has its place and personally use the general pattern in applications but also feel that some use DI in ways that seem to make applications overly complex and more difficult to maintain in the future. My opinion on the subject really doesn’t matter here though since this post is about using an IoC container framework in Silverlight applications.
I’ll walk through a simple example from an existing application that my company is working on and demonstrate how using a dependency injection pattern can help minimize code and simplify changes down the road. If you’re new to the concept of DI and IoC containers I’d recommend reading Martin Fowler’s post on the subject. He provides a good introduction to constructor, setter and interface injection. If I had to sum up DI and the purpose of IoC Containers in a single sentence here’s what I’d say:
Minimize hard coded class names when creating object instances and let IoC containers dynamically look-up types and “inject” them into your application at runtime.
Before jumping into using Autofac in Silverlight let’s take a quick look at the type of problem an IoC container can solve. The following code shows a ViewModel class (see my post of using the MVVM pattern with Silverlight if you’d like more information on what a ViewModel is) that has two constructors:
from Dan Wahlin more here