Software Architecture- C# – Unity 2.0 – First lession

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]

Advertisements

One Response to Software Architecture- C# – Unity 2.0 – First lession

  1. CM says:

    Hello,

    Great post, simple & easy. When are the others coming ?

    Regards,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: