Unity Application BlockがSilverlightに対応したので使ってみた
EnterpriseLibraryから独立したDIコンテナのUnity Application Block(UAB)がバージョン1.2になって、Silverlight対応版が出たので軽く使ってみた。
前に1.1が出た時に使ってみた時のエントリを参照してもらうとUABがどんなものかわかると思う。
ダウンロードは以下のURLから
オブジェクトブラウザでクラス構造なんかを見てると.NETバージョンとパッと見、区別がつかない。
とりあえず、Visual Studio 2008を起動して「Silverlight アプリケーション」プロジェクトを作る。
ページにインジェクション
ページにインジェクションするモデルクラスを作る。
Models/PageModel.cs
using System; using System.Diagnostics; namespace UnitySample.Models { public class PageModel { public PageModel() { } } }
ページクラスにプロパティを追加する。
Page.xaml.cs
using System; using System.Windows; using System.Windows.Controls; using Microsoft.Practices.Unity; using UnitySample.Models; namespace UnitySample { public partial class Page : UserControl { public Page() { InitializeComponent(); } [Dependency] public PageModel PageModel { get { return (PageModel)DataContext; } set { DataContext = value; } } } }
「PageModel」プロパティを定義して、「Dependency」属性でマークしておく。プロパティの値は「DataContext」プロパティで保持しておく。
あとはアプリケーション開始時にルート要素を設定する箇所を以下のように変更する。
App.xaml.cs
using System; using System.Windows; using Microsoft.Practices.Unity; using UnitySample.Models; namespace UnitySample { public partial class App : Application { private IUnityContainer container; // 省略... void Application_Startup(object sender, StartupEventArgs e) { container = new UnityContainer(); this.RootVisual = container.Resolve<Page>(); } void Application_Exit(object sender, EventArgs e) { if(container != null) { container.Dispose(); } } // 省略... } }
「UnityContainer」クラスをインスタンス化し、「Resolve
これでビルドして実行すれば、ページにオブジェクトがインジェクションされているのが確認できる。
Silverlightに特化した機能も無さそうなので、.NETバージョンを使ってた人には普通に使えると思う。