Pages

Wednesday, 8 July 2015

Dependency Injection. What is it?


General:

Dependency injection (DI) 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.

Dependency Injection is one of the priciples, namely the "Dependency Inversion Principle" of the SOLID (Definition)principles of Object Oriented Programming (OOP)

In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling where conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are inverted (i.e. reversed) for the purpose of rendering high-level modules independent of the low-level module implementation details. The principle states:
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.
The principle inverts the way some people may think about object-oriented design, dictating that both high- and low-level objects must depend on the same abstraction.[1]

After all these standard definitions of the DI, we shall try to understand where the need of Dependency Injection came from by looking at the history of OOP and the steps of concepts which lead to DI.

The DI emerged from the need of loose coupling, or in other words to make objects (classes) interact loosely with each other. Then the second question may arise. What is loose coupling and why do we need it?
When we write a complex code, we usually need many objects (in form of classes) and the complex code shall need all those classes to interact with each other in one way or another, in order to accomplish a certain functionality of the system (i.e. for a banking system, customer classes interacting with specific account classes using calculation classes throughout the process).
In principle we can create just one huge class with one function (or method) and stuck everything into it in order to solve our problem. Is this viable? This was actually the functional programming in the 80s and 90s, where companies created their famous legacy codes. However, these companies realized after a while that they are hitting a roadblock when they wanted to expand the code, or maintain for bugs or perform testing on their code to validate it. The need for modular design started emerging along with the Object Oriented Programming and it's principles (refer to SOLID: Definition) .
Soon after some clever people in the software industry started coming up with certain design patterns, architectures and the concept of factoring (refer to Martin Fowler). Some of those design patterns provided some separation in between the interacting classes but were not perfect. Factory pattern, Abstract Factory Pattern, Service Locator pattern were a few of them but really did not satisfy the need for a good loose coupled architecture. (refer
Factories, Service Locators, and Dependency Injection <https://msdn.microsoft.com/en-us/library/dn178469(v=pandp.30).aspx> )

Those design patterns somewhat used the basic principle of Loose Coupling, which is shown below.

 

Basically, Loose Coupling is using an Interface (an intermediary plug) in between the high level class (HLC) and low level class (LLC). An HLC is a class where a detailed operation is performed (as an example some banking computation where interest rate is calculated) and LLC is the class which calls upon the HLC. Those two classes communicate with each other via an Interface. An Interface is a very important concept in OOP. An Interface is basically an empty shell of methods, properties etc. Only a class can implement an Interface method or property. Interface makes (for instance) polymorphism possible in OOP (for more about Interfaces refer to Interfaces (C# Programming Guide)).

1-Now let's take a simple example, using a low level class which inherits from an Interface:

LLClass:XYZ // LLClass inherits from XYZ INterface
{
}

2-Now for the High Level Class:

HLClass
{
Interface XYZ; //Declare Interface
LLClass LLCls = new LLClass(); //Create LLClass
XYZ = LLClass; // Assign the Interface to the Low Level Class, as we want to use the Interface (plug to the LLClass) within the High Level Class
}

Now we can use the Interface (the plug to our Low Level Class) from within our High Level Class. But wait, there is already a problem. We have created an instance of the Low Level Class within the High Level Class, making the HLC dependent to the LLC. So, even though we have an interface at the HLC to plug in to LLC thus avoiding the use of LLC directly, we kept the dependency (to the LLC) when we created the LLC in the first place. How can we avoid this? Well, this is where the Dependency Injection (DI) comes into play.

Idea: We shall create the LLC somewhere else (for instance another class we call a "creator" class) and then inject the Interface XYZ somehow into our HLC. Now, let's look at the following case.

LLClass:XYZ // LLClass inherits from XYZ INterface
{
}

2-Creator class

clsCreator
{
clsCreator()
{
LLClass LLcls = new LLClass(); //Create LLClass
HHClass HHCls= new HHClass(LLCls); //Create HLClass
}
}

3-Now for the High Level Class:

HLClass
{
Interface XYZ; //Declare Interface

HLClass(Interface xyz) // Constructor passing Interface XYZ
{
XYZ = xyz; // Assign the Interface to the Low Level Class, as we want to use the Interface (plug to the LLClass) within the High Level Class
}
}

As we can see now the HLC and LLC are completely separated (i.e. independent of each other), in other words they are loosely coupled via the concept of Dependency Injection. We have simply injected the XYZ Interface (which is a plug to the LLC) into the HLC via the constructor. A similar injection could have been made by using a method or property.

Unity Dependency Container is simply a lightweight framework doing just this plus other goodies. We can use (i.e. add) Unity into our projects (refer to
Adding Unity to Your Application) and start using it for a modular, loosely coupled, easily expandable, maintainable and testable software system design.

Wednesday, 20 May 2015

A Humble Review of Josh Smith's MVVM Article

Foreword:


WPF Programmers who are familiar with MVVM have most probably read one of the first comprehensive articles ever published, written by Josh Smith  WPF Apps With The Model-View-ViewModel Design Pattern ".
This article is rightfully considered one of the best MVVM articles by many and even seen by some as the "premier guideline" article for the MVVM pattern.
Here, in this blog post I will try to analyze the code (can be downloaded from the same Microsoft Magazine at this download page). I will try to make a somewhat detailed review, providing bunch of diagrams assisting my review, in order to make some of the points more clear. I believe diagrams are sometimes a better way to describe a structure as visual guides like diagrams are claimed to be more cognitive and helpful than text.
I will attempt to cover the design in four parts (in 4 blog postings) and will try a top to bottom approach. When necessary, I will make references to other resources or blog posts in order to assist the description. I hope this article would contribute to the programming community and make MVVM design principles more clear.   


Introduction: 

I would strongly recommend the reader first to read the original article written by Josh Smith or at least the first parts of it , before continuing here. Also it is recommended to have the source code in front of you (download page). This is essential to understand what is written below and in the follow-up sections. Here. I will try to avoid repeating Josh's article as much as I can and do not intend to cut/paste excerpts from it (except a few pictures, may be). My intention is not to repeat what Josh has already written, but to complement the original article in my own ways. I think only this way, I can make a contribution, if any. I would like to apologize for all the mistakes (both grammatical and technical) upfront. Hope that this article will add some more value into the original one. I will strongly encourage constructive feedback from readers, which would help me to improve the article for the benefit of all.

Part#1:




The class diagram above shows the structure of the ViewModel design. There are five ViewModels used. We will describe in the final part (4th part) of this article exactly why five ViewModels are used, in other words the logic behind selecting ViewModels. For the time being, we shall take it for granted and carry on with the description. 


The MVVM uses multiple ViewModels, which control their own dedicated View space. The Command structure borrows the principle from Prism, using a separate Command class (class derived from ICommand) called RelayCommand, which is a simplified version of the DelegateCommand of Prism. The MVVM system can be separated into logical operational sections. The first section can be called "Setup" section, which handles all the operations which take place when the program is launched.

Before starting with the "Setup" section, we shall look briefly how the XAML script is laid down.

XAML Structure:


There are 2 general XAML scripts used. First one is called "MainWindow.xaml" and the other is called "MainWindowResources.xaml". The latter serves as a Resource for the MainWindow.xaml. Besides the main XAML script files, there are also UserContol XAML files. One is called "AlllCusomersView.xaml" and the other is called "CustomerView.xaml".




Command Structure:



ICommand methods:

ViewModel Classes
ICommand
CustomerViewModel
Public ICommand SaveCommand
WorkSpaceViewModel
Public ICommand CloseCommand
CommandViewModel
Public ICommand Command

SetUp Section:


When the application is launched, the App.xaml.cs will be executed first automatically by WPF. When the DataContext (i.e.Window.DataContext=viewmodel;) line is hit, the XAML Parser will fire up and start reading the XAML script and first will assign 2 items into the Control Panel HeaderedContentControl via the code at MainWindowViewModel (Note:when a collection is bound to an ItemsControl or ContentControl, all the members of the collection will be listed (rendered) on the itemscontrol (i.e.listcontrol) automatically by the XAML Parser).

//This method is called from the XAML file and executed by XAML parser (when DataContext line is hit at runtime)
       
public ReadOnlyCollection<CommandViewModelCommands
       {
           
get
           {
               
if (_commands == null)
               {
                   
List<CommandViewModel> cmds = this.CreateCommands();
                   _commands = 
new ReadOnlyCollection<CommandViewModel(cmds);
                  //This syntax creates a ReadOnly collection wrapper around the List cmds
               }
               
return _commands;
           }
       }
 
       
List<CommandViewModelCreateCommands()
       {
           
return new List<CommandViewModel>
//This is like List<t>{1,2,5,2,7}; here t=CommandViewodel and before adding we create the object
           {
               
new CommandViewModel(
                   
Strings.MainWindowViewModel_Command_ViewAllCustomers,
                   
new RelayCommand(param => this.ShowAllCustomers())),
 
               
new CommandViewModel(
                   
Strings.MainWindowViewModel_Command_CreateNewCustomer,
                   
new RelayCommand(param => this.CreateNewCustomer()))
           };
       }


  1. Create a new list to contain CommandViewModel objects and add 2 newly created CommandViewModel objects. The Constructor of CommandViewModel creates a 
    new RelayCommand class.
  2. For each command used within the MVVM design, a unique CommandViewModel class is created. 
    Also a unique RelayCommand class is generated (which is linked to the uniquely created CommandViewModel)
  3. When a RelayCommand class is generated, via it's Constructor, the methods "ShowAllCustomers" 
    and "CreateNewCustomer" is passed as delegates from the MainWindowViewModel to the particular RelayCommand.
  4. The purpose of using RelayCommand class is to avoid bunch of Command classes 
    (classes derived from ICommand) within the MVVM design.A different instance of same 
    RelayCommand will handle any command issued from within the MVVM system.
  5. The 2 newly created CommandsViewModel class objects are placed into a list and then wrapped by a Collection in order to be able to assign them to the itemscontrol object's itemsource property.



          Note that "ResXFileCodeGenerator" is used to create strongly typed strings.



After the startup routine is executed, the XAML Parser will know that there are 2 objects (CommandViewModel) in the itemscontrol as element and the XAML Parser uses the additional information (in MainWindowResources XAML script) to render the datatemplate. Here is the section which is responsible for rendering the view under the Control Panel HeaderedContentControl.

 

 
<!--
  This template explains how to render the list of commands on the left
  side in the main window (the 'Control Panel' area).
  -->
  
<DataTemplate x:Key="CommandsTemplate">
    
<ItemsControl IsTabStop="False" ItemsSource="{Binding}" Margin="6,2">
      
<ItemsControl.ItemTemplate>
        
<DataTemplate>
          
<TextBlock Margin="2,6">
            
<Hyperlink Command="{Binding Path=Command}">
              
<TextBlock Text="{Binding Path=DisplayName}" />
            
</Hyperlink>
          
</TextBlock>
        
</DataTemplate>
      
</ItemsControl.ItemTemplate>
    
</ItemsControl>
  
</DataTemplate>


 

Clicking on the hypertext object on the ControlPanel:


Now the XAML Parser knows lots of things regarding the 2 items that has been rendered into the Control Panel. Those items are represented as hypertext on the panel, so they have a command property. When any of them is clicked, XAML Parser will do certain things in the background.  It will go right to the instance of CommandViewModel object, which is related to the hypertext, then will take the right instance of the RelayCommand object instance which is related to this particular CommandViewModel and then run it. Running of the RelayCommand Execute method will call the delegate which points to one of the methods listed at MainWindowViewModel (either  CreateNewCustomer() or ShowAllCustomers(), depending on which hypertext is clicked). Also note that at RelayCommand we need to use "parameter" (i.e. _execute(parameter)) in order to use the correct delegate). The diagram below tries to provide a visual description.


So, how does XAML Parser know where the command (ICommand property) resides? Well, first of all there is a definition at XAML (<Hyperlink Command="{Binding Path=Command}">). However wasn't the DataContext defined as MainWindowViewModel? Yes, but XAML Parser has intelligence. The binding path to Commands (Content="{Binding Path=Commands}"), at which the XAML Parser run the C# code from MainWindowViewModel, made XAML Parser aware of the instances of newly created CommandViewModel and RelayCommand class objects.  So, when the runtime compiler runs, it will not generate an exception, even though the DataContext is not pointing to the class with ICommand Property directly. Below the diagram tries to describe this routing logic.


 If we summarize the action for the command flow for this MVVM Model, we end up with the following diagram.




This command flow offers multiple advantages such as loose coupling (through delegates and ICommand) and modular design for unified command routing (using one RelayCommand class for all commands). There is a collection of CommandViewModel objects for different commands which use the same Command Class (ICommand derived Class) RelayCommand and all the Command executions are handled at the same class namely MainWindowViewModel.


 

This concludes the first part. In the second part of this series, I will focus more on setup and command structure.