Click here to Skip to main content
Click here to Skip to main content

Dependency Injection in WPF using Unity for Dummies

, 6 Jan 2011
Rate this:
Please Sign up or sign in to vote.
This articles discusses the very basics of dependency injection in WPF for those who are new in WPF and Unity.

Introduction

It’s a very common practice that whenever anyone starts writing a 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/designed to some extent by some other person while the core developer can concentrate on business logic. I am not going into 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 handling 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 the 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 objects. 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();

In our application we have one TextDataServices which mainly returns an hardcoded string and we have a TextViewModel in which we have only one string property that is supposed to be set in some UI Label. In MainWindow.XAML, we have two Label controls, one in left (LabelLeft) and one in right (LabelRight) like below:

<Label Content="{Binding Path=LabelContnet,FallbackValue=Left}" 
	Height="28" HorizontalAlignment="Left" Margin="90,85,0,0" 
	Name="LabelLeft" VerticalAlignment="Top" Width="222" Grid.ColumnSpan="2" />
<Label Content="{Binding Path=LabelContnet,FallbackValue=Right}" 
	Grid.Column="1" Height="28" HorizontalAlignment="Left" 
	Margin="90,85,0,0" Name="LabelRight" VerticalAlignment="Top" Width="222" />

Now let’s concentrate on the code behind of this XAML file (MainWindow.xaml.cs):

public partial class MainWindow : Window
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"> class.
        /// </see></summary/>
        /// The text view model.
        public MainWindow(ITextViewModel textViewModel)
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
            DataContext = textViewModel;

            ////Following code actually throws exception as 
            ////Dependency injected after constructed has been called.
            ////LabelLeft.Content = Services.GetData();
        }

        [Dependency]
        public IDataServices Services { get; set; }

        /// <summary>
        /// Handles the Loaded event of the MainWindow control.
        /// </summary>
        /// The source of the event.
        /// The <see cref="System.Windows.RoutedEventArgs"/> 
        /// instance containing the event data.
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            LabelLeft.Content = Services.GetData();
        }

In the constructor, you can see that there is one parameter of type ITextViewModel which will be injected by the Unity when this window will be resolved from OnStartUp event of App.xaml.cs.

In the code behind file, you will also see one property of type IDataServices which has [Dependency] attribute on top of it.
When this window will be resolved during runtime, the object associated with IDataServices will be injected as well. But remember that in the constructor, you will not be able to use this property as this will be injected after the constructor has been called. This type of injection is called property injection.

In order to use the benefit of property injection, you can use this property on Windows.Loaded event or you can write some code on the set property of injectable property.

So when we shall run the code, the left label will be populated from constructor injected TextViewModel and the right label will be populated from property injected DataServices!

I hope this will give you an initial idea about how to use constructor injection and property injection in WPF. When you will be starting a large scale WPF application, you need to use Unity, MVVM and ultimately Prism in your application.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)

About the Author

Mahmudul Haque Azad
Software Developer (Senior) Vizrt Bangladesh
Bangladesh Bangladesh
I am truly versatile and 360 degree Engineer having wide range of development experience in .NET and Java Platform. I am also proficient in system level programming in C++. To me technology is not at all a problem, it’s the client requirement that matters! That is I am ready and comfortable to use any technology to make the business of my client a success.
 
In my five years of experience I have the opportunities to work for fortune 500 companies of US and many renowned clients from Europe.
 
My Linkedin Profile: http://bd.linkedin.com/in/mahmudazad
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 1 PinmemberRetheesh198518-Oct-13 5:53 
GeneralMy vote of 5 PinmemberMorgann Moussier19-Feb-13 6:55 
GeneralMy vote of 2 Pinmemberdanito23429-Nov-12 3:30 
GeneralMy vote of 5 PinmemberMember 837731-Aug-12 9:38 
Very Effective to understand the concept.
GeneralMy vote of 4 Pinmembervet0n12-Feb-12 22:43 
GeneralMy vote of 1 Pinmemberjbachelor9-Mar-11 4:26 
GeneralRe: My vote of 1 PinmemberMahmudul Haque Azad9-Mar-11 17:37 
GeneralRe: My vote of 1 Pinmemberjbachelor12-Mar-11 9:26 
GeneralMy vote of 5 PinmemberAbdul Quader Mamun6-Jan-11 4:28 
GeneralRe: My vote of 5 PinmemberMahmudul Haque Azad24-Jan-11 23:58 
GeneralMy vote of 5 PinmemberSledgeHammer015-Jan-11 6:54 
GeneralRe: My vote of 5 PinmemberMahmudul Haque Azad6-Jan-11 15:44 
GeneralMy vote of 5 PinmemberMember 16043002-Jan-11 8:59 
GeneralRe: My vote of 5 PinmemberMahmudul Haque Azad2-Jan-11 20:30 
GeneralInvalid link PinmemberSindebad28-Dec-10 7:15 
GeneralRe: Invalid link PinmemberMahmudul Haque Azad31-Dec-10 20:22 
Generalbroken link Pinmembermuminbahar27-Dec-10 2:00 
GeneralRe: broken link PinmemberMahmudul Haque Azad31-Dec-10 20:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 6 Jan 2011
Article Copyright 2010 by Mahmudul Haque Azad
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid