Caveman's Blog

My commitment to learning.

Archive for the ‘Design Patterns’ Category

Dependency Injection: Unity Application Block

leave a comment »


In this post I will show you how to use Microsoft Unit Application Block to achieve Dependency Injection. We will see the two methods of configuring the IOC container, firstly the “.config” way and then the “inline” method. Let us take a look at the following code snippet and see how this code can be improved.

class Program
{
    static void Main(string[] args)
    {
        Service svc = new Service();
        svc.Print();
    }
}

public class Service
{
    public void Print()
    {
        Employee empl = new Employee();
        empl.PrintEmployeeTitle("Test Employee");
    }
}

public class Employee
{
    public void PrintEmployeeTitle(string name)
    {
        Console.WriteLine("Employee Name: {0}, Title:{1}", name, "Some Title");
    }
}

What does this code do?

The above code snippet if from a console application, where we are creating an instance of the Service class and are calling the Print method. The Print method in turn instantiates the Employee class and then calls the PrintEmployeeTitle method of the Employee class to print the employee name and title. The PrintEmployeeTitle method writes the name and title of an employee to the console.

What is wrong?

Nothing. While there is nothing wrong with this code, if we closely observer, we can notice that the Employee class instance could not exist without an instance of the Service class. Basically they both are tightly coupled, meaning to say we can only have one implementation of the Employee class to be consumed by the Service class at any given instance of time.

What if we have a scenario when we want to test more than one implementation of the Employee class or if the Employee class implementation is a work-in-progress? Here is where Dependency Injection design pattern comes to our rescue. I hope I have set some context before I explaining about DI and its implementation.

Solving the problem

Decoupling the Employee class life cycle management from the Service class is the primary objective.  The advantage of decoupling the Employee class are that 1) we will be in a position to provide multiple implementations to the Employee class 2) be able to select the kind of implementation that is suitable for our purpose and 3) manage the life cycle of the Employee class. We define an interface IEmployee with one method PrintEmployeeTitle and define two implementations for this demo purpose. The first implementation is what we already had above and the second is a MockEmployee Class.

public class Employee : IEmployee
{
    public void PrintEmployeeTitle(string name)
    {
        Console.WriteLine("Employee Name: {0}, Title:{1}", name, "Some Title");
    }
}

public class MockEmployee : IEmployee
{
    public void PrintEmployeeTitle(string name)
    {
        Console.WriteLine("Employee Name: {0}, Title:{1}", name, "Some MOCK Title");
    }
}

public interface IEmployee
{
    void PrintEmployeeTitle(string name);
}

Let us see how we can delegate the Employee class instantiation to the client (Class:Program; Method: Main) and then inject the Employee object into the Service object.

Dependency Injection

Service class has a dependency on the Employee class and our objective here is inject this dependency into the Service class from the Client. Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time [2]. One way to achieve this is via passing the Employee object reference to the Service class constructor like in the code below:

class Program
{
    static void Main(string[] args)
    {
        Employee empl = new Employee();
        Service svc = new Service(empl);
        svc.Print();
    }
}

public class Service
{
    private IEmployee empl;
    public Service(IEmployee empl)
    {
        this.empl = empl;
    }

    public void Print()
    {
        empl.PrintEmployeeTitle("Test Employee");
    }
}

Another way of injecting the Employee reference into the Service object is via setting the instance of Employee class to an I IEmployee property of the Service class.

class Program
{
    static void Main(string[] args)
    {
        Employee empl = new Employee();
        Service svc = new Service();
        svc.empl = empl;
        svc.Print();
    }
}

public class Service
{
    IEmployee _empl;
    public IEmployee empl
    {
        set
        {
            this._empl = value;
        }
    }
    public void Print()
    {
        _empl.PrintEmployeeTitle("Test Employee");
    }
}

We have so far been able to decouple the Service class and the Employee class, however we still have to create an instance of the Employee class to implement dependency injection. Any change in to the Employee class creation mechanism with require a code change and also a code recompile.  This is the point where IOC framework comes handy in automating the creation and injection of the dependency via just one configuration.

Inversion of control

In software engineering, Inversion of Control (IoC) is an object-oriented programming practice where the object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis [1]. Like discussed earlier we are going to transfer the control of creating the Employee object to the IOC framework rather than keeping it with the Client, mean to say we are performing an “Inversion of Control”.

The configured entities are loaded into an IOC container at run-time and will be injected into the appropriate classes. We can implement .Net Dependency Inject using any one of the following IOC containers:

Microsoft Unity IoC Container

Now let us look at the two ways of configuring and implementing DI using Microsoft Unity Container. Before we can use the Unity container you have to download and install the Microsoft Unit Application Block from the Microsoft Patterns and Practices website. The dll’s necessary for this implementation can be found under the “Drive:/Program Files/Microsoft Unity Application Block x.0/Bin/” folder and should be added as references to your project.

Please accept my apologies for a very crude/rude representation of the client (Class: Program, Method: Main) being able to select one of the three implementations of the Employee class use Dependency Injection via an IOC container.

Application Configuration File

When we have to implement DI using the Application Config file, we have to define Unity block section, define a container and register that namespace and the Class that is getting DI’ed.

<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,
Microsoft.Practices.Unity" />
<container name="TestService">
<register type="UnityFrameworkDemo.IEmployee, UnityFrameworkDemo"
mapTo="UnityFrameworkDemo.MockEmployee, UnityFrameworkDemo">
<lifetime type="singleton" />
</register>
</container>
</unity>

I had to also add a reference of the System.Configuration namespace to the project. Once we have this configuration all set, we have to update the client to 1) load the container that we defined in the configuration and 2) generate the Service class based on the configuration that we have defined:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            container.LoadConfiguration("TestService");
            svc = container.Resolve();
            if (svc != null)
                svc.Print();
            else
                Console.WriteLine("Could not load the Service Class");
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

public class Service
{
    IEmployee _empl;
    public Service(IEmployee empl)
    {
        this._empl = empl;
    }

    public void Print()
    {
        _empl.PrintEmployeeTitle("Test Employee");
    }
}

You would also have noticed that I have added a constructor that accepts parameter of IEmployee type to the Service class. The IOC framework will use this constructor to generate an instance of the Service class and will also pass a reference of the Employee class into the Service instance. Following is the output of using the default Employee implementation:

Now switching to the Mock Employee implementation from the default implementaion is as simple as updating the register element of the configuration with the MockEmployee class name and then we get the following output


Inline

Lastly let us look at how we can configure an implementation inside the client instead of in the application config file. Basically you have to register the Interface and the implementation with the container in the client and your client is ready to make a call to the Service instance methods like shown in the code below:

container.RegisterType();
   svc = container.Resolve();
   if (svc != null)
      svc.Print();

Unity framework basically provides a fantastic approach to decouple the application layer code. You can define several containers and register several classes with the container and be able to enjoy the flexibility by implementing Dependency Injection using the Unity IOC container.

Happy Fourth of July !

References:
1. Inversion of Control – IOC – Wikipedia
2. Dependency Injection – Wikipedia

 
Advertisements

Strategy Pattern

leave a comment »


Strategy pattern is a behavioral software design pattern. In this pattern a family of algorithms can be encapsulated as objects to facilitate the interchangeability of strategies at run-time. In this post I will present an example of a real life scenario where this pattern can be applicable. Brokerage accounts that are used for trading provide the customer with several tax strategies for effective management of gains/losses for a calender year. Typically tax strategies available for a customer of a for Stock/options/Bonds as security types are:

1. First In – First out
2. Last In – First out
3. Highest In – First out
4. Minimum Tax
5. Maximum Gain
6. Average Cost

UML Class diagram:

Considering that all of the above strategies have been implemented using one algorithm per strategy, following is how the code implementation looks like:

    class Program
    {
        static void Main(string[] args)
        {
            CustomerGainCalculator cgc = new CustomerGainCalculator(new FIFOStrategy());
            cgc.ComputeGain();

            cgc = new CustomerGainCalculator(new LIFOStrategy());
            cgc.ComputeGain();

            cgc = new CustomerGainCalculator(new MaximizeGainStrategy());
            cgc.ComputeGain();

            Console.ReadLine();
        }
    }

    //Define an abstract class so that the strategies could be used interchangeability.
    public abstract class StrategyBase
    {
        public abstract void CalculateGain();
    }

    //Implement FIFO Strategy
    public class FIFOStrategy : StrategyBase
    {
        public override void CalculateGain()
        {
            Console.WriteLine("First In - First Out strategy has been called");
        }
    }

    //Implement LIFO Strategy
    public class LIFOStrategy : StrategyBase
    {
        public override void CalculateGain()
        {
            Console.WriteLine("Last In - First Out strategy has been called");
        }
    }

    //Implement Maximum Gain Strategy
    public class MaximizeGainStrategy : StrategyBase
    {
        public override void CalculateGain()
        {
            Console.WriteLine("Maximize Gain strategy has been called");
        }
    }

    //Define the following class with an Aggregated StrategyBase variable. This variable in conjuction
    //with the strategy set at the time of instantiating this class, can be used to compute
    //the gain/loss for a given tax strategy.
    public class CustomerGainCalculator
    {
        private StrategyBase currentStrategy;

        public CustomerGainCalculator(StrategyBase currentStrategy)
        {
            this.currentStrategy = currentStrategy;
        }

        public void ComputeGain()
        {
            this.currentStrategy.CalculateGain();
        }
    }

Following is the output when this program is executed:

Written by cavemansblog

May 4, 2011 at 9:51 pm

Singleton Design Pattern

with one comment


The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist already. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated in any other way, the constructor is made either private or protected. Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, you really have to make it a singleton. [1]

The singleton pattern must be carefully constructed in a multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.[1]

This is definitely not a very good pattern unless used properly. The reason being, the object generated from this class in essence a global object/variable and this is not a good thing in programming world.

Following is a sample implementation of this pattern in C#

public class CSingleton
    {
        public static CSingleton Instance;
        private static object syncLock = new object();

        private CSingleton() { }

        public static CSingleton CreateInstance()
        {
            if (Instance == null)
            {
                lock (syncLock)
                {
                    if (Instance == null)
                    {
                        Instance = new CSingleton();
                    }
                }
            }

            return Instance;
        }
    }

Code Explained
The CSingleton class has a private constructor so that a new object of this class cannot be created outside of this class. Rather we create a static instance
variable of CSingleton type so that the public CreateInstance method can return (or create and return, if not exists) an instance of this class.

What happens when two threads try to invoke the CreateInstance method at the same time?
In a multi threaded environment, there is a chance that a dead lock situation could occur and that the thread safety is not assured. In order to prevent this situation, we use the syncLock approach to lock on the instance creation mechanism, to avoid dead locks.

You can also check out the webcast on design patterns from MSDN [3]. This webcast looks at examples of the Observer, Factory, Composite, and Singleton patterns, and explains how these patterns work and where you would use them in your .NET applications. Following is a another video tutorial I found on youtube about Singleton Design pattern [2]

References:
1. Wikipedia - Singleton Pattern
2. Youtube - The Singleton Design Pattern - codingkriggs
3. MSDN - Webcast: Design Patterns in .NET (Level 200)