TOP
PROFILE
MUSIC TUNE
BBS
LINK

2008年08月05日

UnityとPIABの統合

livedoor Readerによると今度EntLib4.1とUnity1.2がリリースされ、UnityとPIABが統合されるんだそうです。まぁ既存版でも統合は割と簡単にできるので原稿執筆時に検証で作っていたコートを以下に記述しておきます。

まずサンプル用にコンソールアプリを作成してから以下のクラスを追加していきます。

【SampleExtension.cs】

using Microsoft.Practices.Unity;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.ObjectBuilder;
using Microsoft.Practices.Unity.ObjectBuilder;

namespace EntLib4Study
{
    public class SampleExtension : UnityContainerExtension
    {
        public new ExtensionContext Context
        {
            get { return base.Context; }
        }

        protected override void Initialize()
        {
            this.Context.Strategies.AddNew<PolicyInjectionStrategy>(UnityBuildStage.PreCreation);
            this.Context.Policies.SetDefault<IPolicyInjectionPolicy>(new PolicyInjectionPolicy(true)); 
        }
    }
}
【SampleCallHandler.cs】
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;

namespace EntLib4Study
{
    public class SampleCallHandler : ICallHandler
    {
        private int order = 0;

        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            Console.WriteLine("前処理実行!");
            input.MethodBase.Invoke(input.Target, null);
            Console.WriteLine("後処理実行!");
            return input.CreateMethodReturn(null, input.Arguments); 
        }

        public int Order
        {
            get { return order; }
            set { order = value; }
        }
    }
}
【SampleCallHandlerAttribute】
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;

namespace EntLib4Study
{
    public class SampleCallHandlerAttribute : HandlerAttribute
    {
        public SampleCallHandlerAttribute()
        {
        }

        public override ICallHandler CreateHandler()
        {
            return new SampleCallHandler();
        }
    }
}
ここまで追加できたら、あとは呼び出しコードを記述して実行するだけです。
class Program
{
	static void Main(string[] args)
	{
	    IUnityContainer myContainer = new UnityContainer();
	    myContainer.AddExtension(new SampleExtension());

	    myContainer.RegisterType<ILog, Log1>();
	    ILog logger = myContainer.Resolve<ILog>();
	    logger.Output();
	    
	    Console.ReadLine();
	}
}
    
public interface ILog
{
	void Output();
}

public class Log1 : ILog
{
	[SampleCallHandler]
	public void Output()
	{
    		Console.WriteLine("サンプル出力1");
	}
}
実行すると、
"前処理実行!"
"サンプル出力"
"後処理実行!"
と表示されると思います。

※古いMTはpreやcodeだと極小フォントになるので見づらいですが、コピペして適当なエディタにはって頂ければ見やすいかと(^^; Posted by GAMMARAY at 2008年08月05日 15:21 | TrackBack

Comments
SampleCallHandlerのInvokeメソッドってCallHandlerをチェインしなきゃだから、 Console.WriteLine("前処理実行!"); IMethodReturn result = getNext().Invoke(input, getNext); Console.WriteLine("後処理実行!"); こんな感じで、次チェインを呼ばなきゃじゃないですか? Posted by: せきの at 2008年08月06日 14:33
チェインを厳密につなげていくなら確かにgetNextでつなげていく必要がある。でもこのサンプルはそこまでは問わないのだ(^^) Posted by: GAMMARAY at 2008年08月06日 17:35
Post a comment









Remember personal info?