MicrosoftのDIコンテナUnity Application Blockを使用する方法

Microsoft patterns & practices はソフトウェア開発のパターンと実践を体系化したもので、ウォード・カニンガム、マーチン・ファウラー、ラルフ・ジョンソン、ロバート・C・マーチン といった、パターン・アジャイル界隈の著名な開発者も協力している魅力的なプロジェクトです。
http://msdn.microsoft.com/ja-jp/library/ms998572%28en-us%29.aspx
http://msdn.microsoft.com/ja-jp/practices/default%28en-us%29.aspx

そのプロジェクトの1つの依存性注入(DI)のコンテナである、Unity Application Blockは簡単に使用出来ます、その方法を備忘録として残します。

ライブラリのインストール

MSDNより

http://msdn.microsoft.com/ja-jp/library/dd203101%28en-us%29.aspx

Unity Application Block 1.2のインストーラ Unity Application Block 1.2.msi をダウンロードしてインストール。

C:\Program Files\Microsoft Unity Application Block 1.2 にインストールされます。

開発環境

Microsoft Visual C# 2008 Express Edition を使用します。
http://www.microsoft.com/japan/msdn/vstudio/Express/

コンソールアプリケーションの作成

[ファイル]->[新しいプロジェクト]->[コンソールアプリケーション]
プロジェクト UnityExam として新規作成します。

インタフェースと実装クラスを作成する

  • DIコンテナから呼び出すオブジェクトのコードを作成します
  • インタフェース実装クラスを分けて作成します

インタフェース

IService.cs
namespace UnityExam
{
    /// <summary>
    /// サービスインターフェイスです。
    /// </summary>
    public interface IService
    {
        /// <summary>
        /// 処理を実行します。
        /// </summary>
        /// <returns>文字列を返します。</returns>
        string Execute();
    }
}

実装クラス

ServiceImpl.cs
namespace UnityExam
{
    /// <summary>
    /// サービス実装クラスです。
    /// </summary>
    public class ServiceImpl : IService
    {
        /// <summary>
        /// 内容文字列を保存します。
        /// </summary>
        private string content;

        /// <summary>
        /// 内容文字列を提供します。
        /// </summary>
        public string Content
        {
            get { return this.content;}
            set { this.content = value;}
        }

        /// <summary>
        /// 処理を実行します。
        /// </summary>
        /// <returns>内容の文字列を返します。</returns>
        public string Execute()
        {
            return this.content;
        }
    }
}

アプリケーション構成ファイルの追加

ソリューション エクスプローラから プロジェクト名の右クリ->[追加]->[新しい項目の追加]->[アプリケーション構成ファイル]でApp.config を追加して、以下の様に記述します。

App.config

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

  <!--構成セクション-->
  <configSections>
    <section name="unity" type=
      "Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, 
       Microsoft.Practices.Unity.Configuration,
       Version=1.2.0.0, Culture=neutral,
       PublicKeyToken=31bf3856ad364e35" />
  </configSections>

  <!--Unityの設定-->
  <unity>
    <containers>
      <container>
        <types>
          <!--オブジェクトの依存設定-->
          <type type="UnityExam.IService, UnityExam"
            mapTo="UnityExam.ServiceImpl, UnityExam">
            <typeConfig extensionType=
             "Microsoft.Practices.Unity.Configuration.TypeInjectionElement,
              Microsoft.Practices.Unity.Configuration">
              <property name="Content" propertyType="System.String">
                <value value="ほげほげ"/>
              </property>
            </typeConfig>
          </type>
        </types>
      </container>
    </containers>
  </unity>
  
</configuration>

XML設定ファイルのリファレンスはここです http://msdn.microsoft.com/en-us/library/dd203225.aspx

Unityで使用するライブラリの追加設定

System.Configuration.dll
Microsoft.Practices.Unity.dll
Microsoft.Practices.Unity.Configuration.dll
Microsoft.Practices.Unity.StaticFactory.dll

[参照の追加]->[参照追加]->[.NET] よりライブラリへの参照を追加します。

アプリケーションのメインクラス

Program.cs
using System;
using System.Configuration;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using Microsoft.Practices.Unity.StaticFactory;

namespace UnityExam
{
    /// <summary>
    /// メインプログラムです。
    /// </summary>
    class Program
    {
        /// <summary>
        /// アプリケーションのエントリポイントです。
        /// </summary>
        static void Main(string[] args)
        {
            // DIコンテナの初期化
            IUnityContainer container = new UnityContainer();
            UnityConfigurationSection section = (UnityConfigurationSection)
                ConfigurationManager.GetSection("unity");
            section.Containers.Default.Configure(container);

            // DIコンテナからオブジェクトを取得
            IService service = container.Resolve<IService>();

            // オブジェクトを実行する
            string result = service.Execute();

            // コンソール出力して停止
            Console.WriteLine("結果:" + result);
            Console.ReadLine();
        }
    }
}

結果

まとめ

  • XML設定ファイルの記述など、同じくDIコンテナのSpring.NETと変わらない感じで使用出来ます。
  • 今後のMicrosoftの力の入れ具合では、.NET開発においてかなり有望かもしれません。
  • カスタム属性でいろいろ出来そうですが、調べ切れてません、誰か教えてください・・