Monday, December 27, 2010

Dependency Injection in WPF using Unity for Dummies.

It’s a very common practice that whenever anyone starts writing WPF application for the first time, he/she finds it quite similar with traditional windows form application and hence writes all the code in code behind. But after passing few days the code becomes huge and unmanageable.
After passing few days with WPF people get to learn about its data binding feature which reduces the code in code behind a little bit.  
 It is possible to reduce the code in code behind to a great extent if we use Model View ViewModel (MVVM) design pattern. This design pattern actually utilizes WPF data binding feature and provides a good separation of concern. Thus the view (XAML) can be separately developed/design to some extent by some other person while the core developer can concentrate on business logic. I am not going in to details of MVVM, details can be learnt from here.
 Now this separation of concern can be further enriched if we use the power of Unity dependency injection container. Dependency injection is a prime technique for building loosely coupled applications. It provides ways to handle the dependencies between objects. For example, an object that processes customer information may depend on other objects that access the data store, validate the information, and check that the user is authorized to perform updates. Dependency injection techniques can ensure that the customer class correctly instantiates and populates all of these objects, especially where the dependencies may be abstract. You can learn more about Unity from here.
The concept and working procedure of Unity Dependency Injection container may seem magic from Aladdin's genie on the first sight.
Like handing genie, Unity DI container needs to be handled carefully and intelligently. This article mainly covers how we can use this magic easily with some sample code example. (For your convenience I have attached full code base of sample application discussed here.)
Here mainly I have discussed constructor injection and property injection so that people can use it as a quick reference.
The Unity dependency container may be regarded as a “Bank” of useful object. Usually in bank we save our money so that we can use it in time when it is needed.
So on application initialization we shall store all those objects that will be needed by various window/user control etc during the application life cycle like below.

IUnityContainer container = new UnityContainer();
container.RegisterType<IDataServices, TextDataServices>();
container.RegisterType<ITextViewModel, TextViewModel>();
var window = container.Resolve<MainWindow>();
window.Show();

Read more: Codeproject