かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

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

書庫

日記カテゴリ

[WPF][C#][EntLib]UnityでAOP

Enterprise Library 4.1が出てた。
気になるのは、お気に入りのUnityContainerです。バージョンが1.2になるらしい。
その中でも、Policy Application Blockみたいな動きをするInterceptionというのが気になったのでつっついてみた。

AOPといえばロギング!!ということで、ロギングを例にしてみようと思う。まずは、土台作りから。
いつものに、ちょっぴり足したPersonクラスを作る。

namespace UnityEducation.Entities
{
    /// <summary>
    /// 挨拶できるよ
    /// </summary>
    public interface IGreeter
    {
        /// <summary>
        /// 挨拶を返すよ
        /// </summary>
        /// <returns>挨拶の文字列</returns>
        string Greet();
    }

    /// <summary>
    /// いつもの人間クラス
    /// </summary>
    public class Person : IGreeter
    {
        /// <summary>
        /// 名前あるよ
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 挨拶するよ
        /// </summary>
        /// <returns>名前入りの挨拶!</returns>
        public string Greet()
        {
            return string.Format("{0}です!こんにちは!", Name);
        }
    }
}

このGreetメソッドにログを仕込むのが最終目標になる。
続いてMainメソッドで、単純にUnityContainerにPersonを登録して使うところの処理を書く。

とりあえず、UnityContainerとInterceptionを使うのでObjectBuilder2とUnityとUnity.InterceptionExtensionをプロジェクトの参照に追加する。
image

そしてMainメソッドに処理を書いていく。

using System;
using Microsoft.Practices.Unity;
using UnityEducation.Entities;

namespace UnityEducation
{
    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer c = new UnityContainer();

            // インスタンスをコンテナに登録
            c.RegisterInstance<IGreeter>(new Person { Name = "大田" });

            // インスタンスをコンテナから取得して挨拶文を表示
            var ohta = c.Resolve<IGreeter>();
            Console.WriteLine(ohta.Greet());
        }
    }
}

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

やっと土台が完成。これに処理を挟み込んでみようと思う。処理を挟み込むためには、2つのクラスを作らないといけない。

  1. HandlerAttributeを継承した属性
    メソッドとハンドラを結びつけるための目印
  2. ICallHandlerを継承したクラス
    挟み込む処理

まずは属性から。

    /// <summary>
    /// ログを出力するためのAttribute
    /// </summary>
    public class LoggingAttribute : HandlerAttribute
    {
        /// <summary>
        /// 挟み込む処理を返す
        /// </summary>
        public override ICallHandler CreateHandler(IUnityContainer container)
        {
            return new LoggingHandler();
        }
    }

これは、CreateHandlerメソッドをオーバーライドするだけでOK。返すものは、この後作るハンドラです。
ということで、ハンドラを作成する。

/// <summary>
/// ログを出力するハンドラ
/// </summary>
public class LoggingHandler : ICallHandler
{
    public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
    {
        Console.WriteLine("処理開始");
        try
        {
            // 処理を呼ぶ
            return getNext().Invoke(input, getNext);
        }
        finally
        {
            Console.WriteLine("処理終了");
        }
    }

    public int Order { get; set; }
}

ICallHandlerを継承して、Invokeメソッドを実装するだけでOK。最初と最後に処理の開始と終了のメッセージを出すようにしてみた。
実際のGreetメソッドの処理は、getNextデリゲートを呼ぶことで取得できる、getNext()の戻り値に対してInvokeメソッドを呼ぶと本来走る処理が実行される。(同じメソッドに複数のHandlerをセットしてたら別のHandlerの処理が呼ばれる)

そして、PersonクラスのGreetメソッドにLoggingAttributeをセットする。

/// <summary>
/// いつもの人間クラス
/// </summary>
public class Person : IGreeter
{
    /// <summary>
    /// 名前あるよ
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 挨拶するよ
    /// </summary>
    /// <returns>名前入りの挨拶!</returns>
    [Logging] // ログの処理を入れるよ
    public string Greet()
    {
        return string.Format("{0}です!こんにちは!", Name);
    }
}

最後にUnityContainerに対してInterceptionを使うということを示すコードを追加する。

    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer c = new UnityContainer();

            // Interceptionの拡張を追加
            c.AddNewExtension<Interception>();

            // Interceptionの設定
            c.Configure<Interception>().
                // IGreeterにはTransparentProxyInterceptorを使います
                SetInterceptorFor<IGreeter>(new TransparentProxyInterceptor());

            // インスタンスをコンテナに登録
            c.RegisterInstance<IGreeter>(new Person { Name = "大田" });

            // インスタンスをコンテナから取得して挨拶文を表示
            var ohta = c.Resolve<IGreeter>();
            Console.WriteLine(ohta.Greet());
        }
    }

これを実行すると、さっきまでの挨拶一行以外に、処理開始と処理終了も出力されるようになる。
いい感じだ。
image

参考:http://www.pnpguidance.net/Screencast/UnityInterceptionExtensionRemotingPolicyInjectorScreencastUnityTutorials.aspx

投稿日時 : 2008年11月2日 2:01

Feedback

# Cheap Canada Goose 2012/10/17 17:52 http://www.supercoatsale.com

I believe this site contains some really great info for everyone :D. "Experience is not what happens to you it's what you do with what happens to you." by Aldous Huxley.

# burberry bag 2012/10/26 3:20 http://www.burberryoutletscarfsale.com/burberry-ba

of course like your website however you have to check the spelling on quite a few of your posts. Many of them are rife with spelling issues and I in finding it very troublesome to tell the reality on the other hand I'll certainly come again again.
burberry bag http://www.burberryoutletscarfsale.com/burberry-bags.html

# louis vuitton shoes 2012/10/28 3:09 http://www.louisvuittonwallets2013.com/

Appreciate can be the energetic matter towards personal life along with the expansion of that which my partner and i adore.
louis vuitton shoes http://www.louisvuittonwallets2013.com/

# louis vuitton outlet 2012/10/28 3:09 http://www.louisvuittonoutletdiaperbag.com/

At success each of our best friends understand or know our business; of trouble children each of our best friends.
louis vuitton outlet http://www.louisvuittonoutletdiaperbag.com/

# louis vuitton outlet store 2012/10/28 3:09 http://www.louisvuittonbackpack2013.com/

Father‘d throw away your labour in a mankind/women,people who isn‘d able to throw away your spare time for you.
louis vuitton outlet store http://www.louisvuittonbackpack2013.com/

# Burberry Ties 2012/10/28 14:05 http://www.burberryoutletonlineshopping.com/burber

Some truly superb articles on this internet site , thankyou for contribution.
Burberry Ties http://www.burberryoutletonlineshopping.com/burberry-ties.html

# scarf 2012/10/28 14:06 http://www.burberryoutletonlineshopping.com/burber

Some really prime posts on this site, saved to my bookmarks .
scarf http://www.burberryoutletonlineshopping.com/burberry-scarf.html

# wallet 2012/10/28 14:06 http://www.burberryoutletonlineshopping.com/burber

I really like your writing style, wonderful info , appreciate it for putting up : D.
wallet http://www.burberryoutletonlineshopping.com/burberry-wallets-2012.html

# burberry bag 2012/10/28 14:06 http://www.burberryoutletonlineshopping.com/burber

Merely a smiling visitant here to share the love (:, btw outstanding design. "Individuals may form communities, but it is institutions alone that can create a nation." by Benjamin Disraeli.
burberry bag http://www.burberryoutletonlineshopping.com/burberry-tote-bags.html

# qmkUCsTcCRyqKkLqEo 2015/01/11 21:23 varlog

GBqxdd http://www.FyLitCl7Pf7kjQdDUOLQOuaxTXbj5iNG.com

# xfTuTCnlbcClqmx 2015/02/04 7:11 Salvatore

I'll send you a text http://www.jennylin.net/bio.html Elimite Lice "(Netanyahu's address) will blow away the smokescreen the Iranians are putting up in a bid to buy time as they move ahead on their nuclear breakout option," an Israeli official said, describing the point at which Iran will have enough enriched uranium to build a bomb quickly should it decide to do so.

# ZZprmcqlxo 2015/02/05 12:15 Bernardo

Until August http://www.retendo.com.pl/sklep/ cheap domperidone uk Ashlee Simpson getting cuddly with Evan Ross at Avenueâ€?s weekly Monday-night party. ... Katrina Bowden making out with new hubby Ben Jorgensen at the Fashionable Hostess & HostCommittee.com party at the Darby. ... John Forté surprising guests, including Rachel Roy, Pras Michel and Kelly Bensimon, at restaurateur Omar Hernandezâ€?s birthday bash at Omarâ€?s in the West Village. ... Tony Danza working out hard at the upper West Sideâ€?s Reebok Sports Club.

# UualUshouaYCqMPpqa 2015/02/06 16:35 Frances

I'm not sure http://www.glandyficastle.co.uk/starling.html Slimfast 123 The administration continues to urge both sides in Egypt to show restraint, as violence rages in the country. In the latest outbreaks, more than 50 people reportedly were killed and hundreds were injured in clashes outside a military building in Cairo.

# vAIZsUhgJhvLe 2015/02/06 16:35 Bennett

Remove card http://www.wonderbra.ca/my-favorites/ tenormin 25 tablet The study focused on the Western Electricity CoordinatingCouncil as an area with strong solar resources; theinterconnected region includes western U.S. states, Canadianprovinces and northern Mexico.

# QLVJfoNqwd 2015/02/07 20:41 Sofia

I'm unemployed http://www.robertrathbone.co.uk/index.php/blog Yasmin Tablets Metzger testified that Jackson seemed �desperate� in April 2009 � two months before his death � when he asked for intravenous sleep medication during a private meeting at his rented mansion. He said the singer indicated he was having trouble sleeping in the run-up to his doomed �This Is It� comeback concert series in London.

# KwNGabexEhfSGg 2015/02/08 14:10 Douglas

Special Delivery http://www.sporttaplalkozas.com/sporttaplalkozas/sporttaplalkozas-program 1000 loan from direct lender for someone with bad credit In August, Rinaldi said PES has a "multiyear agreement" withJP Morgan, that he did not expect surprises, but that he did notknow how JP Morgan's intention to sell would play out. Rinaldigave no further comment on Wednesday.

# BejgqoXpxdgmq 2015/02/08 14:10 Lorenzo

Do you know the address? http://atecuccod.com/index.php/hogyan-vasaroljon uk cash loans This meant that a special unit that monitored his cell and one other was not operating. A control room that was tasked with covering for the unit did not have access to a crucial CCTV camera in Zygier&#039;s cell and a monitoring diary was not filled in.

# DgZCDlQmwttgegCY 2015/02/08 14:11 Sophia

I really like swimming http://www.sporttaplalkozas.com/sporttaplalkozas/sporttaplalkozas-program high loan personal risk Police sources told local Fox News affiliate WJBK that around three weeks ago, Commander Dwayne Love was asked to advise officers that their bullet proof vests were ready for collection. He forwarded to commanders an email containing the spreadsheet, which listed all of the orders. They forwarded it to the supervisors, who forwarded it on to the officers.

# ETMEZtWFLFdYoAb 2015/02/10 5:44 Archie

Have you got any experience? http://poderesmentales.com/duocobra/ Dose Keflex If Macyâ€?s or other stores want to create excitement, I say they just start hosting Thanksgiving themselves.  Letâ€?s not even pretend itâ€?s a family day.  Just grab a buddy and head down to Macyâ€?s around noon for some appetizers in the cosmetics department.  Dinner will be served in the housewares section, while you watch an endless loop of product demonstrations on the TV monitors.  Dessert tables will be set up throughout all the other departments, so you can enjoy a slice of pie while you pick out sweaters for Grandma and some trendy junior fashions for your teen.

# vObPkqrOcDZqnbqxEp 2015/02/10 5:44 Claud

I can't stand football http://www.milliput.com/about.html Aciclovir Cream The commission, led by Howard Davies, is due to produce an interim report on capacity expansion this year and recommendations on a long-term fix - most likely a choice between expanding Heathrow, building a new airport or creating a joint hub - after the 2015 general election.

# ODUBSUCGcyYfAG 2015/02/10 5:44 DE

I'm unemployed http://digitallocksmithsinc.com/get-informed/ allopurinol interactions Internet users can be charged with defamation if postings containing rumors are visited by 5,000 users or reposted more than 500 times, according to a judicial interpretation issued this month by China's top court and prosecutor.

# uIVIKZyIjxHh 2015/02/11 6:55 Jimmy

I'd like to send this to http://www.theferrerspartnership.com/profile-of-trevor-potter loan calculate The cubs are in good health and weigh appropriate amounts for their age, said giant panda nursery keeper Amy Allagnon. They are slowly gaining more eyesight and hearing and can scoot around but can't yet crawl or stand up on all four legs yet, she said.

# bajqOAMXBz 2015/02/11 6:56 Mohammad

We need someone with experience http://parkavenuebrussels.com/index.php/tips cash box with lock The Agency has closed down 72 websites offering to supply Melanotan to UK customers within the last three months and says it continues to monitor the situation. It says anyone who has suffered side-effects which they suspect may be as a result of using this product should report it via the Agency's Yellow Card Scheme.

# gfFyCfYMWuuSLG 2015/02/26 10:56 Ricardo

The line's engaged http://www.nude-webdesign.com/website-design-development/ aripiprazole purchase The 1.8 tcf estimate, given in a resources report bypetroleum consultants Netherland, Sewell & Associates, issimilar to a preliminary estimate made by Texas-based NobleEnergy, which is leading the development of the well.

# bdPuYymkUtEQC 2015/02/26 10:56 Jeromy

Remove card http://www.nude-webdesign.com/client-portfolio-page/ does abilify 15 mg look like Heather Couper, former president of the British Astronomical Association, told BBC Radio 4&rsquo;s Today programme: &ldquo;The meteors are debris from a comet called Comet Swift-Tuttle, which was discovered by two astronomers called Lewis Swift and Horace Tuttle in 1862

# jXLILCzmEiUdGmq 2015/02/27 21:13 Travis

I live here http://zoombait.com/z-hog/ Alesse Generic Brand "This is a very serious matter for the customer and for us. We will not tolerate any wrongdoing and that is why we have referred this matter to the Police," he said. " It is also why I have immediately initiated a programme of change and corporate renewal."

# EjsTWIOpINqwvuhc 2015/02/27 21:13 Caleb

A staff restaurant http://www.europanova.eu/tag/crise/ bimatoprost beard growth Cable companies need larger scale through consolidation,whether through mergers or joint ventures, the so-called "Kingof Cable" said in an interview on the sidelines of the annualAllen and Co media conference in Sun Valley, Idaho.

# rcxzccihMoOIpnKo 2015/02/27 21:14 Goodsam

Who's calling? http://www.europanova.eu/tag/federalisme/ bimatoprost preis BOSTON � Slain Boston Marathon bombing suspect Tamerlan Tsarnaev was named as a participant in an earlier triple homicide by a man who was subsequently shot to death while being questioned by authorities, according to a filing made by federal prosecutors in the case against his brother, surviving bombing suspect Dzhokhar Tsarnaev.

# hqpatKZJNysjg 2015/04/07 13:34 Jaime

I'd like to take the job http://www.occedb.org/statutes Order Cozaar Online Firstly, the role of the Scottish government. Just 14 per cent claim to have a â€?very good ideaâ€? of how power is divided up between Holyrood and Westminster, while 40 per cent claim to have â€?very little ideaâ€?. Just over half think  Scottish Parliament elections are of equal importance to Westminster and 18 per cent believe it is more important. Not exactly a vote of confidence for an institution looking for more powers.

# JLODYHBDnHzX 2015/04/07 13:34 Gaylord

Some First Class stamps http://www.europanova.eu/entreprendre-leurope/ cost bimatoprost Stamps said she first thought of this low-tech method when she noticed patients weren't having their sense of smell tested. The cranial nerve associated with smell is often one of the first areas impacted by cognitive decline. Peanut butter in particular is a "pure odorant," Stamps said, meaning its scent is only detected by this nerve.

タイトル
名前
Url
コメント