DCSIMG
Using Unity Injection API - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2012 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Using Unity Injection API

Using Unity Injection API

In some previous posts I Unity Application Block
explained how to use the
Unity configuration section in
dependency injection scenarios.
In this post I’m going to show  
how to use some aspects of the
Unity injection API
.

Unity Injection API
When you use Unity sometimes you want to inject dependencies in runtime and
not in configuration files. The use of Unity injection API can help you do it very simple. 
In the Unity application block use the Microsoft.Practices.Unity namespace in order
to use the injection API. All the classes that can be used to inject dependencies has
a prefix of Injection and they include the InjectionConstructor, InjectionProperty and etc.
Every injection class inherit the InjectionMember abstract class. 
The InjectionMember is the base class for objects that can be used to configure what
class members get injected by the Unity container.

Main Classes of Injection API
There are three injection aspects that are leveraged by the Unity application block.
The three aspects are constructor, properties and methods injection. In the injection
API
the classes that represent these aspects are:

  •  InjectionConstructor - A class that holds the collection of information for a
    constructor, so that the Unity container can be configured to call this constructor.
  • InjectionProperty - This class stores information about which properties to inject,
    and will configure the Unity container accordingly.
  • InjectionMethod - An InjectionMember that configures the Unity container to
    call a method as part of buildup.

Unity Injection API Example
In the following example I use the SqlDatabase class:

    public class SqlDatabaseDatabase

    {

        #region Members

        private string _connString;

        #endregion

        #region Properties

        public ILogger Logger { get; set; }

        public IValidator<int> Validator { get; set; }

        #endregion

        #region Ctor

        public SqlDatabase(string connString)

        {

            _connString = connString;   

        }

        #endregion

    }

All the other classes and interfaces I use can be found in the previous posts I wrote
in the Unity application block series.
The following example shows how to use the injection API:

   IUnityContainer container = new UnityContainer();

   container.RegisterType<ILogger, FileLogger>();

   container.RegisterType<Database, SqlDatabase>();

   container.RegisterType<IValidator<int>, Validator<int>>();

   container.Configure<InjectedMembers>().

   ConfigureInjectionFor<SqlDatabase>(

      new InjectionConstructor(

         ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString),

      new InjectionProperty("Logger"),

      new InjectionProperty("Validator"));

   var database = container.Resolve<Database>();

The container’s Configure method is the main method to use in order to inject members.
It returns an InjectedMembers class which I use it’s ConfigureInjectionFor to inject
aspects for a particular type (in the example the SqlDatabase class). 
In the example you can see that I inject the FileLogger into the Logger property,
the Validator<int> into the Validator property and a connection string from
the list of connection strings in the configuration file to the constructor. In the end of the
process the database object will be constructed with the appropriate validator, logger
and connection string all in one instruction of code.
As I wrote earlier the injection API is simple and intuitive.

Summary
To sum up the post, Unity has an injection API that helps to inject dependencies aspects
in runtime. The API is simple to use and I showed an example of how to use it in the post.
I suggest to write some code with the injection API in order to get familiar with it.

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# August 1, 2008 9:57 AM

Vardi said:

הי

אני מאוד אוהב את הכתיבה שלך.

תמשיך עם העבודה הטובה.

אני אשמח עם תעזור לי לפרסם את הסדנא של

www.e4d.co.il/.../Course.aspx

# August 2, 2008 2:14 AM

DefeatEd said:

I think your last line is wrong, shouldn't it be Resolving the SqlDatabase type?

# August 2, 2008 1:55 PM

Gil Fink said:

Hi DefeatEd,

The last line is correct. You resolve the type of Database and therefore get back the SqlDatabase into the database variable. In the Unity registration process you can register for the Database abstarct class every concrete class you built. The Resolve method meant to get back in runtime the one of the registered types - the SqlDatabase in my example.

# August 2, 2008 2:13 PM

Gil Fink said:

Thanks Eyal :-),

You can read my conference recommandation here: blogs.microsoft.co.il/.../expert-days-2008.aspx

I won't be able to come but if I could I would have taken one of the workshops in that week.

# August 2, 2008 2:17 PM