Software Architecture-Dependency Injection with Unity for Constructor Injection

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

Advertisements

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: