Software Architecture-C# Unity 2.0 – Basic Features

February 19, 2011

I have covered different elements of Unity 2.0, in last we posts as:

>>Software Architecture- C# – Unity 2.0 – First lession

>>Software Architecture C-Sharp Unity-2.0 Second Lession

>>Software Architecture – C#- Unity-2.0-Creating Instance Registrations

>>Software Architecture-Dependency Injection with Unity for Constructor Injection

>>Software Architecture- Interception / Decorator Pattern with Unity

Hope you have liked these posts!


Software Architecture-Interception with Unity(Decorator pattern)

January 16, 2011

Previous Related posts:
Software Architecture- C# – Unity 2.0 – First lession
Software Architecture C-Sharp Unity-2.0 Second Lession
Software Architecture – C#- Unity-2.0-Creating Instance Registrations
Software Architecture-Dependency Injection with Unity for Constructor Injection

According to Unit Documentation:

Unity interception enables you to effectively capture calls to objects and add additional functionality to the target object. Interception is useful when you want to modify the behavior for individual objects but not the entire class, very much as you would do when using the Decorator pattern. It provides a flexible approach for adding new behaviors to an object at run time.

For definition of decorator pattern, please visit wiki link as below:
http://en.wikipedia.org/wiki/Decorator_pattern
Interception process is explained below as:

For exact details about Interception by Unity visit, MSDN at:
http://msdn.microsoft.com/en-us/library/ff660891(v=pandp.20).aspx
Lets create a Calculator which provide implementation for adding 2 numbers.
For that create a Calculator class which implements calculator interface as below:

public interface ICalculator
    {
        [InterceptorAttribute]
         int AddMe(int a, int b);
    }
class Calculator:ICalculator
    {
        public int AddMe(int a, int b)
        {
            if (a == 0 && b == 0)
                throw new Exception("Dummy input....");
            else
            return a + b;
        }
    }

Note that AddMe method in interface is decorated with a attribute named “InterceptorAttribute” which is explained below:
Let implement ICallHandler, as below:

// Summary:
    //    Handlers implement  ICallHandler interface and are called for each invocation of the
    //     pipelines that they're included in.
    class InterceptorCallHandler : ICallHandler
    {
        // Summary:
        //     Implement this method to execute your handler processing.
        //
        // Parameters:
        //   input:
        //     Inputs to the current call to the target.
        //
        //   getNext:
        //     Delegate to execute to get the next delegate in the handler chain.
        //
        // Returns:
        //     Return value from the target.
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {           
            Console.WriteLine("Entering "+ this.GetType().Name + "'s Method Invoke" );
            
            //Pre-Method call processing
            Console.WriteLine("Pre-Method call processing - Input Parameters:");
            foreach (var parameter in input.Arguments)
            {
                Console.WriteLine(parameter.ToString());
            }
            // Actual call to method
            IMethodReturn result = getNext()(input, getNext);

            //Post method call processing
            Console.WriteLine("Post method call processing - Output Parameters:" + ((result.ReturnValue!=null)? result.ReturnValue.ToString():""));

            // Exception passed by call
            if (result.Exception != null)
            {
                Console.WriteLine("Exception :" + result.Exception.Message);                                                
                Console.WriteLine("Stacktrace :");
                Console.WriteLine(Environment.StackTrace);
            }
            Console.WriteLine("Leaving " + this.GetType().Name + "'s Method Invoke");
            
            return result;
        }

        public int Order { get; set; }
    }

Let define an attribute as below:

// Summary:
    //    HandlerAttribute is Base class for handler attributes used in the attribute-driven interception
    //     policy.
    class InterceptorAttribute : HandlerAttribute
    {

        // Summary:
        //     Derived classes implement this method. When called, it creates a new call
        //     handler as specified in the attribute configuration.
        //
        // Parameters:
        //   container:
        //     The Microsoft.Practices.Unity.IUnityContainer to use when creating handlers,
        //     if necessary.
        //
        // Returns:
        //     A new call handler object.
        public override ICallHandler CreateHandler(Microsoft.Practices.Unity.IUnityContainer container)
            {            
                 return new  InterceptorCallHandler();
                }
    }

Now every thing is wired up, so let do some testing with above implementation as below:

// define container
            IUnityContainer myContainer = new UnityContainer();
            // add extension for interception
            myContainer.AddNewExtension<Interception>();
            myContainer.RegisterType<ICalculator, Calculator>().Configure<Interception>()
                .SetInterceptorFor<ICalculator>(  new InterfaceInterceptor());
            // resolve
            ICalculator iCal = myContainer.Resolve<ICalculator>();
            //Test case  1
            Console.WriteLine("Going to call to AddMe method with input 3, 4:");
            Console.WriteLine("Call to AddMe method with input 3, 4 - Result is: " + iCal.AddMe(3, 4));
            //Test case  2
            try
            {
                Console.WriteLine("Going to call to AddMe method with input 0, 0:");
                Console.WriteLine("Call to AddMe method with input 0, 0 - Result is: " + iCal.AddMe(0, 0));
            }
            catch { }
            Console.ReadKey();  

The Output will be as below:

The above code create unity Container, then a extension for interception is added, then type is registered, resolved to get a instance of calculator.
Then in Test Case 1, AddMe method is called with input 3,4. This call is intercepted via InterceptorAttribute and Pre-processing before the call [Input parameters are printed to Console] and Post-processing after the call is done [Result parameters are printed to Console]. Anything can be done in these locations. This is decorator pattern.
Then in Test Case 2, AddMe method is called with input 0,0, this call is again intercepted via InterceptorAttribute and Preprocessing before the call [Input parameters are printed to Console]and Post-Processing after the call is done[Exception is handled and Call stack is printed on Console.] This is again decorator pattern implementation.

Download complete source code here.
[After downloading the file, rename “unity2interceptioncalculatorapp-zip.doc” to “Unity2InterceptionCalculatorApp.zip” and extract the files]

So that is how interception works in Unity Container.
Keep Enjoying Unity 2.0


Software Architecture-Dependency Injection with Unity for Constructor Injection

January 16, 2011

Previous Related posts:
Software Architecture- C# – Unity 2.0 – First lession
Software Architecture C-Sharp Unity-2.0 Second Lession
Software Architecture – C#- Unity-2.0-Creating Instance Registrations

Now consider Dependency Injection with Unity for Constructor Injection

1. Single Constructor Automatic Injection
For automatic constructor injection, simply specify as parameters of the constructor the dependent object types and specify the concrete type, or specify an interface or base class for which the Unity container contains a registered mapping.

  class BusinessManager
    {
        ILogger myLogger;
        // Constructor for case 1
        public BusinessManager(ILogger logger)
        {
            myLogger = logger;
            Console.WriteLine("BusinessManager's constructor called ...." + DateTime.Now.ToString());
        }
        
        public void DoSomeThing()
        {
            Console.WriteLine("BusinessManager's DoSomeThing() called ...." + DateTime.Now.ToString());
            myLogger.Write("Hello..........");
        }

    }

And some operations on class as:

  
  UnityContainer container4 = new UnityContainer();
  // Case 1 :Specifying Named Type Mappings
  container4.RegisterType<ILogger, EmailLogger>();
  BusinessManager manager = container4.Resolve<BusinessManager>();
  manager.DoSomeThing();

The output will be as:

2. Specifying Named Type Mappings

Consider a new sample class as:

  
class BusinessManager
    {
        ILogger myLogger;
        public  BusinessManager([Dependency("Email")]  ILogger logger)
        {
          myLogger = logger;
          Console.WriteLine("BusinessManager's constructor called ...." + DateTime.Now.ToString());
        }
        public void DoSomeThing()
        {
            Console.WriteLine("BusinessManager's DoSomeThing() called ...." + DateTime.Now.ToString());
            myLogger.Write("Hello..........");
        }

    }

And some operations on class as:

  
// Case 2:Specifying Named Type Mappings
UnityContainer container44 = new UnityContainer();
container44.RegisterType<ILogger, EmailLogger>("Email");
BusinessManager manager44 = container44.Resolve<BusinessManager>();
manager44.DoSomeThing();

The output will be as:

In this code above we defined a constructor in the BusinessManager class that takes as a parameter the concrete type of the dependent class, and apply a Dependency attribute to the parameter that specifies the name of the registered mapping to use.

3. Multiple Constructor Injection Using an Attribute
When a target class contains more than one constructor with the same number of parameters, you must apply the InjectionConstructor attribute to the constructor that the Unity container will use to indicate which constructor the container should use. As with automatic constructor injection, you can specify the constructor parameters as a concrete type, or you can specify an interface or base class for which the Unity container contains a registered mapping.
Consider modified class as:

  
class BusinessManager
    {
        ILogger myLogger;
        // Constructor for case 1
        public BusinessManager(EmailLogger logger)
        {
            myLogger = logger;
            Console.WriteLine("BusinessManager's constructor called ...." + DateTime.Now.ToString());
        }
        // Constructor for case 2
        public BusinessManager([Dependency("Email")]  ILogger logger)
        {
            myLogger = logger;
            Console.WriteLine("BusinessManager's constructor called with Dependency attribute ...." + DateTime.Now.ToString());
        }
        [InjectionConstructor]
        public BusinessManager(WinTraccerLogger logger)
        {
            myLogger = logger;
            Console.WriteLine("BusinessManager's constructor called  with InjectionConstructor attribute...." + DateTime.Now.ToString());
        }
        public void DoSomeThing()
        {
            Console.WriteLine("BusinessManager's DoSomeThing() called ...." + DateTime.Now.ToString());
            myLogger.Write("Hello..........");
        }

    }

With some operations on class as:

  
// Case 3:Multiple Constructor Injection Using an Attribute
UnityContainer container444 = new UnityContainer();                   
BusinessManager manager444 = container444.Resolve<BusinessManager>();
manager444.DoSomeThing();

The ouput will be as:

According to Unity Documentation:

How Unity Resolves Target Constructors and Parameters
When a target class contains more than one constructor, Unity will use the one that has the InjectionConstructor attribute applied. If there is more than one constructor, and none carries the InjectionConstructor attribute, Unity will use the constructor with the most parameters. If there is more than one constructor that is the “longest” with the same number of parameters, Unity will raise an exception.

Similarly, Property (Setter) Injection and Method Call Injection can be peformed as common form of Dependency Injection.

Download complete source code here.
[After downloading the file, rename “unitytestapp-zip.doc” to “unitytestapp.zip” and extract the files]

Enjoy coding with Unity 2.0


Software Architecture – C#- Unity-2.0-Creating Instance Registrations

January 10, 2011

Previous Related posts:
Software Architecture- C# – Unity 2.0 – First lession
Software Architecture C-Sharp Unity-2.0 Second Lession

In the sequence, consider following Unity Code for analysis:

// Create container
UnityContainer container3 = new UnityContainer();
ILogger elogger = new EmailLogger();
// Step 1
Console.WriteLine("Step 1");
// Register an instance
container3.RegisterInstance(elogger);
// Resolve on basis of instance
ILogger logger3 = container3.Resolve<ILogger>();
// call a method
logger3.Write("Hello World....!!!");

// Step 2
Console.WriteLine("Step 2");
// Register named instance
container3.RegisterInstance("Email",elogger);
// Resolve on basis of named istance
ILogger logger33 = container3.Resolve<ILogger>("Email");
// call a method
logger33.Write("Hello World....!!!");

//Step 3
Console.WriteLine("Step 3");
//Register named intance with ContainerControlledLifetimeManager as life time manager
container3.RegisterInstance("Email",elogger , new ContainerControlledLifetimeManager());
// Resolve
ILogger logger333 = container3.Resolve<ILogger>("Email");
// call a method
logger333.Write("Hello World....!!!");

//Register named intance with HierarchicalLifetimeManager as life time manager
container3.RegisterInstance("Email",elogger , new HierarchicalLifetimeManager());
// Resolve
ILogger logger3333 = container3.Resolve<ILogger>("Email");
// call a method
logger3333.Write("Hello World....!!!");                                  
 

The output of code is as:

In Step 1, a instance is registered,then resolved and method is called.
UnityContainerExtensions static class has extension method for UnityContainer which registers a default instance mapping with the container so that it returns the specified instance when a Resolve method requests an instance of the type TInterface (which can be an implemented interface instead of the actual type). The container takes over the lifetime of the instance.
Explained as below:

public static IUnityContainer RegisterInstance<TInterface>(this IUnityContainer container, TInterface instance);    
//
// Summary:
//     Register an instance with the container.
//
// Parameters:
//   container:
//     Container to configure.
//
//   instance:
//     Object to returned.
//
// Type parameters:
//   TInterface:
//     Type of instance to register (may be an implemented interface instead of
//     the full type).
//
// Returns:
//     The Microsoft.Practices.Unity.UnityContainer object that this method was
//     called on (this in C#, Me in Visual Basic).
//
// Remarks:
//      Instance registration is much like setting a type as a singleton, except
//     that instead of the container creating the instance the first time it is
//     requested, the user creates the instance ahead of type and adds that instance
//     to the container.
//     This overload does a default registration and has the container take over
//     the lifetime of the instance.
 

In step 2, a named intance is created and named resolve is called.
UnityContainerExtensions static class has extension method for UnityContainer which registers a named instance mapping with the container so that it returns the specified instance when a Resolve method requests an instance of the type TInterface (which can be an implemented interface instead of the actual type) and the specified name. The container takes over the lifetime of the instance. Names are case sensitive.
Explained as below:

public static IUnityContainer RegisterInstance<TInterface>(this IUnityContainer container, string name, TInterface instance);
//
// Summary:
//     Register an instance with the container.
//
// Parameters:
//   instance:
//     Object to returned.
//
//   container:
//     Container to configure.
//
//   name:
//     Name for registration.
//
// Type parameters:
//   TInterface:
//     Type of instance to register (may be an implemented interface instead of
//     the full type).
//
// Returns:
//     The Microsoft.Practices.Unity.UnityContainer object that this method was
//     called on (this in C#, Me in Visual Basic).
//
// Remarks:
//      Instance registration is much like setting a type as a singleton, except
//     that instead of the container creating the instance the first time it is
//     requested, the user creates the instance ahead of type and adds that instance
//     to the container.
//     This overload automatically has the container take ownership of the instance.

In step 3, a named intance is created and named resolve is called with container life manager specified.
UnityContainerExtensions static class has extension method for UnityContainer which registers a named instance mapping with the container so that it returns the specified instance when a Resolve method requests an instance of the type TInterface (which can be an implemented interface instead of the actual type) and the specified name. Names are case sensitive. Also registers the specified LifetimeManager instance with the container to manage the lifetime of the returned object.

Explained as below:

public static IUnityContainer RegisterInstance<TInterface>(this IUnityContainer container, string name, TInterface instance, LifetimeManager lifetimeManager);   
//
// Summary:
//     Register an instance with the container.
//
// Parameters:
//   instance:
//     Object to returned.
//
//   container:
//     Container to configure.
//
//   name:
//     Name for registration.
//
//   lifetimeManager:
//     Microsoft.Practices.Unity.LifetimeManager object that controls how this instance
//     will be managed by the container.
//
// Type parameters:
//   TInterface:
//     Type of instance to register (may be an implemented interface instead of
//     the full type).
//
// Returns:
//     The Microsoft.Practices.Unity.UnityContainer object that this method was
//     called on (this in C#, Me in Visual Basic).
//
// Remarks:
//      Instance registration is much like setting a type as a singleton, except
//     that instead of the container creating the instance the first time it is
//     requested, the user creates the instance ahead of type and adds that instance
//     to the container.

Download complete source code here.
[After downloading the file, rename “unitytestapp-zip.doc” to “unitytestapp.zip” and extract the files]

Enjoy coding Unity 2.0….


Software Architecture C-Sharp Unity-2.0 Second Lession

January 9, 2011

Related Post: Software Architecture C# Unity-2.0 First Lession

So in order to explore Unity more,Consider a small logging sample with a Interface as:

 public interface ILogger
    {
        void Write(string message);
    }

First I introduce, a dummy implementation of ILogger named WinTraccerLogger as:

class WinTraccerLogger : ILogger
    {
        public WinTraccerLogger()
        { Console.WriteLine("WinTraccerLogger:Constructors.............\n"); }
        public void Write(string message)
        {
    Console.WriteLine("WinTraccerLogger's Write method :" + string.Format("{0}: {1}",
                                          DateTime.Now,
                                          message));        
        }
    }

Secondly, I introduced, a dummy implementation of ILogger named EmailLogger as:

 class EmailLogger : ILogger
    {
        public EmailLogger()
        { Console.WriteLine("EmailLogger:Constructors.............\n"); }
        public void Write(string message)
        {
      Console.WriteLine("EmailLogger's Write method: " + string.Format("{0}: {1} \n",
                                          DateTime.Now,
                                          message));
        }
    }

Consider the Test case sample below:

// create a container
UnityContainer container2 = new UnityContainer();
// Step 1: registration name examples
Console.WriteLine("Step 1: Registration name examples");                     
container2.RegisterType<ILogger, EmailLogger>("Email");
container2.RegisterType<ILogger, WinTraccerLogger>("WinTraccer");
ILogger logger2 = container2.Resolve<ILogger>("Email");
logger2.Write("Hello World....!!!");
ILogger logger22 = container2.Resolve<ILogger>("WinTraccer");                    
logger22.Write("Hello World....!!!");
                                        
//Step 2: Resolve all types
Console.WriteLine("Step 2: Resolvge all types");
IEnumerable<ILogger> lstLogger = container2.ResolveAll<ILogger>();                    
foreach (var item in lstLogger)
{
item.Write("Hello World....!!!");
}

Outcome of Test case is as:

In step 1,of above sample shows, Unity provides a method named Resolve that you can use to resolve an object by type by providing a registration name. So 2 types are registered wih name “Email” for EmailLogger and “WinTraccer” for WinTraccerLogger.Corresponding log write method is called

In Step 2, of above sample, Unity provides a ResolveAll method which return all the Types, then there is a loop to call write mehtod of all the resolved types.

Download complete source code here.
[After downloading the file, rename “unitytestapp-zip.doc” to “unitytestapp.zip” and extract the files]


Software Architecture- C# – Unity 2.0 – First lession

January 9, 2011

My Team scrum Master – Akhtar pointed out that Unity is good container for Dependency Injection in .Net plate form, so I decided to explore it a little bit.
Current version of Unity is 2.0
According documentation, Unity is expressed as:

Unity is a lightweight, extensible dependency injection container that supports interception, constructor injection, property injection, and method call injection. You can use Unity in a variety of different ways to help decouple the components of your applications, to maximize coherence in components, and to simplify design, implementation, testing, and administration of these applications.
Unity is a general-purpose container for use in any type of Microsoft® .NET Framework-based application. It provides all of the features commonly found in dependency injection mechanisms, including methods to register type mappings and object instances, resolve objects, manage object lifetimes, and inject dependent objects into the parameters of constructors and methods and as the value of properties of objects it resolves.

So in order to explore Unity more, I created a small logging sample with a Interface as:

 public interface ILogger
    {
        void Write(string message);
    }

I introduced, a dummy implementation of ILogger named EmailLogger as:

 class EmailLogger : ILogger
    {
        public EmailLogger()
        { Console.WriteLine("EmailLogger:Constructors.............\n"); }
        public void Write(string message)
        {
            Console.WriteLine("EmailLogger's Write method: " + string.Format("{0}: {1} \n",
                                          DateTime.Now,
                                          message));
        }
    }

Following are main elements of unity:
1. UnityContainer: A simple class which provides extensible dependency injection container.
2. UnityContainerExtensions class has a main method as:

public static IUnityContainer RegisterType(this IUnityContainer container, params InjectionMember[] injectionMembers) where TTo : TFrom;

Its details are as below:

        //
        // Summary:
        //     Register a type mapping with the container.
        //
        // Parameters:
        //   container:
        //     Container to configure.
        //
        //   injectionMembers:
        //     Injection configuration objects.
        //
        // Type parameters:
        //   TFrom:
        //     System.Type that will be requested.
        //
        //   TTo:
        //     System.Type that will actually be returned.
        //
        // Returns:
        //     The Microsoft.Practices.Unity.UnityContainer object that this method was
        //     called on (this in C#, Me in Visual Basic).
        //
        // Remarks:
        //      This method is used to tell the container that when asked for type TFrom,
        //     actually return an instance of type TTo. This is very useful for getting
        //     instances of interfaces.
        //     This overload registers a default mapping and transient lifetime.

3. UnityContainerExtensions class has a main method as:

public static T Resolve(this IUnityContainer container, params ResolverOverride[] overrides);

Its details are as below:

//
        // Summary:
        //     Resolve an instance of the default requested type from the container.
        //
        // Parameters:
        //   container:
        //     Container to resolve from.
        //
        //   overrides:
        //     Any overrides for the resolve call.
        //
        // Type parameters:
        //   T:
        //     System.Type of object to get from the container.
        //
        // Returns:
        //     The retrieved object.

On basis of above elements consider test case as:

Console.Write("Testing Started.................\n");
UnityContainer container = new UnityContainer();
                    container.RegisterType<ILogger, EmailLogger>();
                    ILogger logger = container.Resolve<ILogger>();
                    ILogger logger0 = container.Resolve<ILogger>();
                    logger.Write("Hello World....!!!");
                    logger0.Write("Hello World....!!!");

The output of above code wil be as:

Note here that a each time Resolve is called, constructor is callled- means new instance of object is created. This is because by default TransientLifetimeManager is used for life time management6 of objects.

Now consider a second test case as:

Console.Write("Testing Started.................\n");
UnityContainer container1 = new UnityContainer();
                    container1.RegisterType<ILogger, EmailLogger>( new ContainerControlledLifetimeManager() );
                    ILogger logger1 = container1.Resolve<ILogger>();
                    ILogger logger11 = container1.Resolve<ILogger>();
                    ILogger logger111 = container1.Resolve<ILogger>();
                    logger1.Write("Hello World....!!!");
                    logger11.Write("Hello World....!!!");
                    logger111.Write("Hello World....!!!");

The output of above code wil be as:

In abvoe code ContainerControlledLifetimeManager is used as life time manager for objects which effectively implements a singleton behavior for objects. So for 3 Resolve call, only single object is created-one call to constrcutor is given.

Hope this simple code explains the basics of Unity as Dependency Injection container.

Download complete source code here.
[After downloading the file, rename “unitytestapp-zip.doc” to “unitytestapp.zip” and extract the files]