かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

わんくまBlogが不安定になったため、前に書いてたはてなダイアリーにメインを移動します。
かずきのBlog@Hatena
技術的なネタは、こちらにも、はてなへのリンクという形で掲載しますが、雑多ネタははてなダイアリーだけに掲載することが多いと思います。
コメント
プログラマ的自己紹介
お気に入りのツール/IDE
プロフィール
経歴
広告
アクセサリ

書庫

日記カテゴリ

[C#][EntLib]UnityContainerの拡張について

さて、UnityContainerの拡張のお話。
UnityContainerExtensionを実装する形で作成するという例をちょっと前に書いた。

今日は、もうちょっと掘り下げてみようと思う。
前回の例では、UnityContainerExtensionのInitializeメソッドでフレームワークで使用するクラス群を登録しちゃえば便利そうだね~と言った。
今回は、それに加えてUnityContainerがクラスのインスタンスを生成する過程に割り込む方法を書いてみようと思う。

UnityContainerExtensionにはContextというプロパティがある。Contextの型はExtensionContextという型で、ここに色々なメソッドやプロパティが定義されている。
その中の1つにStrategiesというプロパティがある。

ここに、Microsoft.Practices.ObjectBuilder2.IBuilderStrategyを実装したクラスをAddメソッドを使って追加することで色々出来るようになる。

IBuilderStrategyインターフェースのメソッドは、以下の4つになる。

  1. PostBuildUp
  2. PostTearDown
  3. PreBuildUp
  4. PreTearDown

この中で、オブジェクトの生成に関わるメソッドは、PreBuildUpとPostBuildUpの2つになる。
~TearDownのほうは、IUnityContainerのTearDownメソッドを呼んでインスタンスを破棄するときに使われるので、今回はとりあえず無視する。

とりあえず、日本語で詳しく書かれた情報が見当たらなかったので適当に実装して動きを見てみるために適当な実装をでっちあげた。

public class MyStragety : IBuilderStrategy
{
    private string stage;
    public MyStragety(string stage)
    {
        this.stage = stage;
    }

    #region IBuilderStrategy メンバ

    public void PostBuildUp(IBuilderContext context)
    {
        Print("PostBuildUp", context);
    }

    public void PostTearDown(IBuilderContext context)
    {
        // no op
    }

    public void PreBuildUp(IBuilderContext context)
    {
        Print("PreBuildUp", context);
    }

    public void PreTearDown(IBuilderContext context)
    {
        // no op
    }

    private void Print(string method, IBuilderContext context)
    {
        Console.WriteLine(stage + ", " + method);
    }

    #endregion
}

これを登録するExtensionも作成する。

public class MyExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        Context.Strategies.Add(new MyStragety("Creation"), UnityBuildStage.Creation);
        Context.Strategies.Add(new MyStragety("Initialization"), UnityBuildStage.Initialization);
        Context.Strategies.Add(new MyStragety("Lifetime"), UnityBuildStage.Lifetime);
        Context.Strategies.Add(new MyStragety("PostInitialization"), UnityBuildStage.PostInitialization);
        Context.Strategies.Add(new MyStragety("PreCreation"), UnityBuildStage.PreCreation);
        Context.Strategies.Add(new MyStragety("Setup"), UnityBuildStage.Setup);
        Context.Strategies.Add(new MyStragety("TypeMapping"), UnityBuildStage.TypeMapping);
    }
}

さっきは、説明しなかったけどStrategiesのAddメソッドには、Stageと呼ばれるものも一緒に登録する。
これがどういう意味を持つのかわからないので、一応全部登録して動きを見てみることにした。

そして、このExtensionを追加して動きを確認するサンプルを作って動きを見てみた。

public interface IFoo
{
    void Foo();
}
public class FooImpl : IFoo
{
    public void Foo() { Console.WriteLine("Foo"); }
}

class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();
        container.AddNewExtension<MyExtension>();
        container.RegisterType<IFoo, FooImpl>();

        Console.WriteLine("Resolveするよ!!");
        var foo = container.Resolve<IFoo>();
        foo.Foo();

    }
}

これを実行すると、ちょっと長いけど下のような実行結果になった。

Resolveするよ!!
Setup, PreBuildUp
TypeMapping, PreBuildUp
Lifetime, PreBuildUp
PreCreation, PreBuildUp
Creation, PreBuildUp
Initialization, PreBuildUp
PostInitialization, PreBuildUp
PostInitialization, PostBuildUp
Initialization, PostBuildUp
Creation, PostBuildUp
PreCreation, PostBuildUp
Lifetime, PostBuildUp
TypeMapping, PostBuildUp
Setup, PostBuildUp
Foo

Setup, TypeMapping, Lifetime, PreCreation, Creation, Initialization, PostInitializationの順番でPreBuildUpが呼ばれて、今度は逆順にPostBuildUpが呼ばれてるのがわかると思う。
きっと各フェーズで何か処理がされているのだろうけど、ちょっと調べるのは今度にして簡単なサンプルを作ってみた。

サンプルは、IFooインターフェースを実装したクラスを作るときにこっそりインスタンスに細工をするというものにしてみた。

public interface IFoo
{
    void Foo();
}
public class FooImpl : IFoo
{
    public void Foo() { Console.WriteLine("Foo"); }
}

public class FooDecoratorExtension : UnityContainerExtension
{
    protected override void Initialize()
    {
        // 無条件にIFooをデコレートするStrategyを仕込む
        Context.Strategies.Add(
            new FooDecoratorStrategy(),
            UnityBuildStage.Creation);
    }
}

/// <summary>
/// IFooを作成しようとした場合に、無条件にFooDecoratorでデコレートする
/// </summary>
public class FooDecoratorStrategy : IBuilderStrategy
{
    #region IBuilderStrategy メンバ

    public void PostBuildUp(IBuilderContext context)
    {
        // IFooならFooDecoratorでくるむ
        if (context.Existing is IFoo)
        {
            context.Existing = new FooDecorator((IFoo)context.Existing);
        }
    }

    public void PostTearDown(IBuilderContext context)
    {
    }

    public void PreBuildUp(IBuilderContext context)
    {
    }

    public void PreTearDown(IBuilderContext context)
    {
    }

    #endregion
}


/// <summary>
/// IFooを飾り付けるよ
/// </summary>
public class FooDecorator : IFoo
{
    private IFoo org;

    public FooDecorator(IFoo org)
    {
        this.org = org;
    }

    public void Foo()
    {
        Console.WriteLine("デコレート!!");
        org.Foo();
        Console.WriteLine("デコレート!!");
    }
}


class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();
        container.AddNewExtension<FooDecoratorExtension>();
        container.RegisterType<IFoo, FooImpl>();

        Console.WriteLine("Resolveするよ!!");
        var foo = container.Resolve<IFoo>();
        foo.Foo();

    }
}

これを実行すると、以下のような結果になる。

Resolveするよ!!
デコレート!!
Foo
デコレート!!

これは、フレームワークとかで特定の型の場合に何か細工入れ込むとかステキな処理が出来そうだ。

投稿日時 : 2008年11月5日 13:08

Feedback

# louis vuitton speedy 2012/10/28 3:08 http://www.louisvuittonoutletdiaperbag.com/

Friendships continue for the instant each individual one partner considers bigger hook favorable position over the many other.
louis vuitton speedy http://www.louisvuittonoutletdiaperbag.com/

# cheap burberry bags 2012/10/28 18:12 http://www.burberryoutletonlineshopping.com/burber

Only wanna remark on few general things, The website style is perfect, the content material is really wonderful. "All movements go too far." by Bertrand Russell.
cheap burberry bags http://www.burberryoutletonlineshopping.com/burberry-tote-bags.html

# Cheap Canada Goose 2012/10/30 20:16 http://www.supercoatsale.com

As soon as I found this internet site I went on reddit to share some of the love with them.
Cheap Canada Goose http://www.supercoatsale.com

# Adidas Climacool Ride 2012/10/30 20:17 http://www.adidasoutle.com/adidas-shoes-adidas-cli

Regards for helping out, great info .
Adidas Climacool Ride http://www.adidasoutle.com/adidas-shoes-adidas-climacool-ride-c-1_3.html

# Adidas Forum Mid 2012/10/30 20:19 http://www.adidasoutle.com/adidas-shoes-adidas-for

Utterly indited articles , thankyou for selective information .
Adidas Forum Mid http://www.adidasoutle.com/adidas-shoes-adidas-forum-mid-c-1_6.html

# Nike Free 3.0 V4 Damen 2012/10/30 21:18 http://www.nikefree3runschuhe.com/

Won't connect with others that happen to be relaxing to be with. Make friends who'll team to jimmy your lifestyle over.
Nike Free 3.0 V4 Damen http://www.nikefree3runschuhe.com/

# mia clarisonic mia coupon 2012/10/30 21:18 http://www.clarisonicmia-coupon.com/

I favor take a look at by virtue of what you do, however , by virtue of who also What i am after i are in your wallet.
mia clarisonic mia coupon http://www.clarisonicmia-coupon.com/

# burberry outlet 2012/11/01 9:37 http://www.burberryoutletlocations.com

Merely wanna say that this is very beneficial , Thanks for taking your time to write this.
burberry outlet http://www.burberryoutletlocations.com

# burberry bag 2012/11/03 1:48 http://www.burberryoutletscarfsale.com/burberry-ba

I really like your writing style, great info , thanks for posting : D.
burberry bag http://www.burberryoutletscarfsale.com/burberry-bags.html

# wallet 2012/11/03 1:48 http://www.burberryoutletscarfsale.com/accessories

I really appreciate this post. I have been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thx again!
wallet http://www.burberryoutletscarfsale.com/accessories/burberry-wallets-2012.html

# Burberry Watches 2012/11/03 1:48 http://www.burberryoutletscarfsale.com/accessories

I truly enjoy reading through on this site, it has excellent blog posts. "The living is a species of the dead and not a very attractive one." by Friedrich Wilhelm Nietzsche.
Burberry Watches http://www.burberryoutletscarfsale.com/accessories/burberry-watches.html

# mens shirts 2012/11/03 1:48 http://www.burberryoutletscarfsale.com/burberry-me

I have recently started a site, the info you provide on this website has helped me tremendously. Thanks for all of your time & work.
mens shirts http://www.burberryoutletscarfsale.com/burberry-men-shirts.html

# burberry womens shirts 2012/11/03 1:48 http://www.burberryoutletscarfsale.com/burberry-wo

Really excellent info can be found on web site. "Prayer is the wing wherewith the soul flies to heaven, and meditation the eye wherewith we see God." by Ambrose of Milan.
burberry womens shirts http://www.burberryoutletscarfsale.com/burberry-womens-shirts.html

# cheap tie 2012/11/03 1:49 http://www.burberryoutletscarfsale.com/accessories

But a smiling visitant here to share the love (:, btw outstanding design and style. "Competition is a painful thing, but it produces great results." by Jerry Flint.
cheap tie http://www.burberryoutletscarfsale.com/accessories/burberry-ties.html

# grqCfeoatVF 2014/08/27 9:20 http://crorkz.com/

wvxDRz Hello there, You have done a fantastic job. I will definitely digg it and personally suggest to my friends. I am sure they will be benefited from this web site.

# bDotzGYQNTEF 2014/08/29 10:29 http://indiapropertieshub.yolasite.com/

Hi! Do you know if they make any plugins to assist with SEO? I'm trying to get my blog to rank for some targeted keywords but I'm not seeing very good success. If you know of any please share. Cheers!

# taUKYSNWvajKQj 2014/09/05 23:58 https://www.youtube.com/watch?v=bmyZcX8nn50

I am often to blogging and i really admire your content. The article has actually peaks my interest. I am going to bookmark your website and preserve checking for new information.

# FGuwqGFVmlMZDoGzkmc 2014/09/08 19:12 http://www.arrasproperties.com/

F*ckin' amazing things here. I'm very happy to see your article. Thanks so much and i am having a look ahead to touch you. Will you kindly drop me a mail?

# isApVaYCmBmzKGSTfT 2014/09/09 19:49 http://www.arrasproperties.com/category/properties

you have an amazing blog here! would you like to make some invite posts on my blog?

# pHOVCpXncy 2014/09/10 19:40 http://www.nobisca.com

F*ckin' amazing issues here. I'm very glad to look your post. Thanks so much and i'm looking forward to contact you. Will you please drop me a mail?

# WZfLosvXtQlPyhLsg 2014/09/18 0:09 http://youtu.be/g68g0W6gbIc

you could have an excellent weblog here! would you prefer to make some invite posts on my blog?

# Why viewers still use to read news papers when in this technological world everything is presented on web? 2019/04/16 17:44 Why viewers still use to read news papers when in

Why viewers still use to read news papers when in this technological world everything is presented on web?

# My brother recommended I might like this blog. He was totally right. This post truly made my day. You can not imagine simply how much time I had spent for this information! Thanks! 2019/08/19 21:40 My brother recommended I might like this blog. He

My brother recommended I might like this blog.
He was totally right. This post truly made my day. You
can not imagine simply how much time I had spent for this information! Thanks!

# UpaQZMfUvV 2021/07/03 3:25 https://amzn.to/365xyVY

It as wonderful that you are getting ideas from this article as well as from our discussion made here.

# BkGxifRwMZusS 2021/07/03 4:54 https://www.blogger.com/profile/060647091882378654

Thanks again for the blog article.Thanks Again. Want more.

# re: [C#][EntLib]UnityContainer??????? 2021/08/08 14:15 arthritis medication hydroxychloroquine

choloquine https://chloroquineorigin.com/# hydroxycloro

# lSMAZWCoZkwCeWIIv 2022/04/19 10:28 johnanz

http://imrdsoacha.gov.co/silvitra-120mg-qrms

# buy doxycycline online - https://doxycyclinesale.pro/# 2023/04/22 4:05 Doxycycline

buy doxycycline online - https://doxycyclinesale.pro/#

# prednisone - https://prednisonesale.pro/# 2023/04/22 15:11 Prednisone

prednisone - https://prednisonesale.pro/#

# cytotec online - https://cytotecsale.pro/# 2023/04/29 4:41 Cytotec

cytotec online - https://cytotecsale.pro/#

# canada prescriptions https://pillswithoutprescription.pro/# 2023/05/16 9:33 PillsPro

canada prescriptions https://pillswithoutprescription.pro/#

# generic prednisone for sale https://prednisonepills.pro/# - prednisone without rx 2023/06/05 5:20 Prednisone

generic prednisone for sale https://prednisonepills.pro/# - prednisone without rx

# what is the best ed pill https://edpill.pro/# - ed pills cheap 2023/06/27 14:38 EdPills

what is the best ed pill https://edpill.pro/# - ed pills cheap

# the best ed pills https://edpills.ink/# - medication for ed 2023/07/27 0:52 EdPills

the best ed pills https://edpills.ink/# - medication for ed

# doxycycline generic https://doxycycline.forum/ doxycycline 100mg online 2023/11/25 13:14 Doxycycline

doxycycline generic https://doxycycline.forum/ doxycycline 100mg online

# men's ed pills https://edpills.tech/# gnc ed pills 2023/12/23 8:12 EdPills

men's ed pills https://edpills.tech/# gnc ed pills

# These are really wonderful ideas in about blogging. You have touched some fastidious points here. Any way keep up wrinting. 2024/10/23 4:28 These are really wonderful ideas in about blogging

These are really wonderful ideas in about blogging.
You have touched some fastidious points here. Any way keep up wrinting.

タイトル
名前
Url
コメント