Thursday, January 21, 2010

Dependency Injection Made Easy

Part of the whole fun with doing 'ard'd samples is just the fun of doing something not quit PC but the bottom line really is doing clear and concise samples that are easy to understand. Granted MVVM really was getting out of control so there was allot of passion about this but in general simple, clear and concise works much better in teaching ideas and concepts especially for less then geniuses such as my self. Today's post comes out of some editing of a video blog post on MVVM Made Simple and some one's mention of using dependency injection over standard binding to a ViewModel in MVVM. That said that is what I'll show today. The most simple implementation of Dependency Injection. Take a look at this sample Xaml code from a few from a Silverlight app using MVVM Made Simple:

<Simple:AViewModelClass />

You can see that we are setting the data context to the view in XAML to a particular ViewModel. In MVVM the idea is that the View is data bound to a ViewModel using DataContext and typically done in Xaml. From here Dependency Injection is one of those concepts that is over complicated by most poeple and mixed with MVVM that makes all of it harder to understand. So really if you are already reading this I'm making the assuming you have worked with MVVM Made Simple and understands it complete. That being the case Dependency Injection is a tweak to MVVM that allows from a programmatic standpoint more flexibility as to the ViewModel being bound to the View.

The Xaml we looked at above is removed or at least the contents of DataContext is removed but in our codebehind we can do this:

this.DataContext = new AViewModelClass();

and now you know Dependency Injection... for 'ards (like me) at least. :)


  1. for more info on DI

  2. Are you Injecting the Depedency in code behind or simply Binding !?

  3. so in the sample in this post it is in the code (C#)