かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

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

書庫

日記カテゴリ

[C#][MEF]Managed Extensibility Framework入門 その2

[C#][MEF]Managed Extensibility Framework入門 その1

ということで、MEF Preview 5を試してみます。
プログラムを始めるときは、何事もHello worldからです!!ということで、MEFでも慣例に沿ってHello worldを作っていこうと思います。

プロジェクトの作成~下準備

ということで、早速コンソールアプリケーションを「MEFHelloWorldApp」という名前で新規作成します。MEF Preview 5を解凍したフォルダの下のbinにあるSystem.ComponentModel.Composition.dllを参照に追加します。

プロジェクトを作成したら、最初に、MEFのコンテナの初期化を行います。
とりあえずソースの上にusing(VBならImports)に

  1. System.ComponentModel.Composition
  2. System.ComponentModel.Composition.Hosting

の2つを追加します。

C#

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace MEFHelloWorldApp
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

VB

Imports System.ComponentModel.Composition
Imports System.ComponentModel.Composition.Hosting

Module Module1

    Sub Main()

    End Sub

End Module

そしてMainにコンテナの初期化コードを書いていきます。

C#

// コンテナのインスタンスを生成
var container = new CompositionContainer();
// これにコンテナに登録するクラスを指定する
var batch = new CompositionBatch();
// ここでコンテナに登録するクラスを指定する

container.Compose(batch);

// 好きな処理を書く

VB

' コンテナのインスタンスを生成
Dim container As New CompositionContainer
' これにコンテナに登録するクラスを指定する
Dim batch As New CompositionBatch
' ここでコンテナに登録するクラスを指定する

container.Compose(batch)

' 好きな処理を書く

これで下準備完了です。

Hello worldの作成

ここまでは、どのプログラムでも共通する処理です。ここからついにHello worldを作りこんでいきます。
作るクラスとしては、Hello worldという文字列を返すGreeterと、それを標準出力へ印字するGreetApplicationの2つのクラスを作ります。これは、説明もいらない程簡単なクラスなのでさくっとコードを載せます。

C#

using System;

namespace MEFHelloWorldApp
{
    public class Greeter
    {
        public string Greet()
        {
            return "Hello world";
        }
    }

    public class GreetApplication
    {
        public Greeter Greeter { get; set; }

        public void Run()
        {
            Console.WriteLine(this.Greeter.Greet());
        }
    }
}

VB

Public Class Greeter
    Public Function Greet() As String
        Return "Hello world"
    End Function
End Class

Public Class GreetApplication
    Private _greeter As Greeter
    Public Property Greeter() As Greeter
        Get
            Return _greeter
        End Get
        Set(ByVal value As Greeter)
            _greeter = value
        End Set
    End Property

    Public Sub Run()
        Console.WriteLine(Me.Greeter.Greet())
    End Sub
End Class

ここからMEF固有のことをやります。
まず、今回のアプリケーションの形は、GreetApplicationが、Greeterを使うという形になります。そのため、GreetApplicationではGreeterクラスを取得できないといけません。逆にGreeterクラスは、他のクラスに自分を使ってもらえないといけません。

そういうのを表すために属性を追加します。追加する属性は2つで

  1. System.ComponentModel.Composition.ExportAttribute
    自分を外部の人が使えるようにする。
  2. System.ComponentModel.Composition.ImportAttribute
    外部の人を取り込む。

です。

ということで、今回はGreeterクラスにExport属性をつけて、GreetApplicationのGreeterプロパティにImport属性をつけます。

C#

using System;
using System.ComponentModel.Composition;

namespace MEFHelloWorldApp
{
    [Export]
    public class Greeter
    {
        public string Greet()
        {
            return "Hello world";
        }
    }

    public class GreetApplication
    {
        [Import]
        public Greeter Greeter { get; set; }

        public void Run()
        {
            Console.WriteLine(this.Greeter.Greet());
        }
    }
}

VB

Imports System.ComponentModel.Composition

<Export()> _
Public Class Greeter
    Public Function Greet() As String
        Return "Hello world"
    End Function
End Class

Public Class GreetApplication
    Private _greeter As Greeter

    <Import()> _
    Public Property Greeter() As Greeter
        Get
            Return _greeter
        End Get
        Set(ByVal value As Greeter)
            _greeter = value
        End Set
    End Property

    Public Sub Run()
        Console.WriteLine(Me.Greeter.Greet())
    End Sub
End Class

コンテナにクラスを登録して使う

粒がそろったので、MEFのコンテナに登録して使ってみようと思います。
CompositionBatchのAddPart(object)メソッドを使ってインスタンスを登録します。

C#

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace MEFHelloWorldApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // コンテナのインスタンスを生成
            var container = new CompositionContainer();
            // これにコンテナに登録するクラスを指定する
            var batch = new CompositionBatch();
            // ここでコンテナに登録するクラスを指定する

            // GreeterとGreetApplicationを追加する
            batch.AddPart(new Greeter());
            var app = new GreetApplication();
            batch.AddPart(app);

            container.Compose(batch);

            // 好きな処理を書く
            app.Run(); // Hello world!!
        }
    }
}

VB

Imports System.ComponentModel.Composition
Imports System.ComponentModel.Composition.Hosting

Module Module1

    Sub Main()
        ' コンテナのインスタンスを生成
        Dim container As New CompositionContainer
        ' これにコンテナに登録するクラスを指定する
        Dim batch As New CompositionBatch
        ' ここでコンテナに登録するクラスを指定する

        ' GreeterとGreetApplicationを追加する
        batch.AddPart(New Greeter())
        Dim app As New GreetApplication
        batch.AddPart(app)

        container.Compose(batch)

        ' 好きな処理を書く
        app.Run()
    End Sub

End Module

これで、コンテナにGreeterクラスのインスタンスとGreetApplicationクラスのインスタンスを登録してGreetApplicationのRunを実行してます。恐らくcontainer.Compose(batch)の時点で、Export属性やImport属性を見て適切にコンテナが依存性を解決してくれてると思われます。

証拠にこのアプリケーションを実行すると、GreetApplicationのGreeterプロパティに値を設定してるコードが無いにもかかわらず、Hello worldが表示されます。
image

ということでMEFのHello worldでした。
今回の方法だと、コンテナに登録するインスタンスを全て事前に作っておかないといけないのか!?って感じですけど、ちゃんとフル機能使えば、アセンブリにある属性のついたクラス全部を対象にしたり、フォルダに入ってるアセンブリから読み込んだり夢広がる設計になっています。

ということで、今日はここまで!続きもやるかも・・・?(C#とVB両方用意するの疲れた)

投稿日時 : 2009年6月30日 23:05

Feedback

# Supra High Tops 2012/12/08 3:59 http://suprafashionshoes1.webs.com/

I really like your writing style, superb info, thanks for putting up :D. "Much unhappiness has come into the world because of bewilderment and things left unsaid." by Feodor Mikhailovich Dostoyevsky.

# supra uk 2012/12/08 6:58 http://supratkstore.webs.com/

I dugg some of you post as I thought they were handy handy

# エルメスの販売 2012/12/14 20:38 http://www.hermespairs.info/category/エルメスバーキン

I go along with the too costly garbage remark. I can't stand the start looking, sound or perhaps feel belonging to the Beats.

# sac longchamps 2012 2012/12/15 15:47 http://www.saclongchampachete.com/category/sac-lon

Its chance are which means fantastic and additionally working design so rapid.

# burberry london 2013 2012/12/15 22:48 http://www.burberryuksale.org/category/burberry-20

gripping streams of remarks bursting outside the photos.

# cuir longchamps 2012/12/16 17:50 http://www.saclongchampachete.com/category/sacs-lo

I know everybody may hate on them, but I do not think they start looking so terrible.

# エルメスクリスマス 2012/12/17 20:54 http://www.hermespairs.info/category/エルメス時計

We found a great many great DVDs that marilyn and i were excited to look at again. Over the course of two months.

# michael kors femme 2012/12/18 2:00 http://sac2012femmes.wordpress.com

I guess I'm sure not alone having every one of the enjoyment at this point!

# longchamp uk sale 2012/12/21 4:17 http://bagslongchamp.webeden.co.uk

If they will sound very good I'd utterly wear these in the house.

# www.b66.fr 2013/02/27 8:35 http://www.b66.fr/

To everyone you should be anyone, on the other hand to just one customer you should be on earth. www.b66.fr http://www.b66.fr/

# www.c55.fr 2013/02/28 22:18 http://www.c55.fr/

Won't it's the perfect time who will be comfy to get along with. Make friends who will pressure anyone to pry one self it. www.c55.fr http://www.c55.fr/

# ckgucci 2013/02/28 22:18 http://www.ckguccifr.fr/

The entire saddest approach girl individual will be perched appropriate alongside them finding out you can‘tonne keep these things. ckgucci http://www.ckguccifr.fr/

# Code Promo Spartoo 2013/03/04 23:05 http://www.c88.fr/

On large choice the best contacts fully understand our company; through adversity we understand the best contacts. Code Promo Spartoo http://www.c88.fr/

# destockprix 2013/03/06 14:50 http://www.f77.fr/

If you ever would undoubtedly prevent your solution from the an enemy, notify it all in no way an acquaintance. destockprix http://www.f77.fr/

# Jordan Retro 11 2013/03/06 20:44 http://www.nikerow.com/

Romances keep going when ever each single great friend seems bigger hook transcendence within the all the other. Jordan Retro 11 http://www.nikerow.com/

# Air Jordan Retro 4 2013/03/06 20:48 http://www.jordanretro4air.com/

I really like you do not attributable to you, however attributable to individuals who My business is actually i'm you've made. Air Jordan Retro 4 http://www.jordanretro4air.com/

# casquette chicago bulls 2013/03/14 4:27 http://www.a77.fr/

Friendly relationship might golden thread this connections the entire paper hearts pores and skin country. casquette chicago bulls http://www.a77.fr/

# destockchine 2013/03/24 0:26 http://d77.fr/

Fancy, friendly relationship, value, really don't link people today as much as a well-known hatred for anything at all. destockchine http://d77.fr/

# Laredoute 2013/04/07 5:05 http://ruezee.com/

I'd guess that Deity is wanting all of us in order to satisfy a handful of incorrectly visitors earlier than meeting the correct one, to make certain once we completely meet the woman / man, exploration find out how to become relieved. Laredoute http://ruezee.com/

# brandalley 2013/04/07 11:50 http://rueree.com/

Take care not to communicate your entire enjoyment to just one a lesser amount of lucky enough over your self. brandalley http://rueree.com/

# Bijoux Fantaisie 2013/04/07 17:02 http://www.ruedee.com/

Want excellent account statement within your perfectly worth, rely pals. Bijoux Fantaisie http://www.ruedee.com/

# coach factory outlet online 2013/04/07 22:38 http://www.coachfactoryoutlet77.com/

A suitable my brother are probably not someone, still someone are invariably some sort of my brother.

# tati 2013/04/08 0:22 http://ruenee.com/

Someone basically find with provides is going to be purchased from we. tati http://ruenee.com/

# Magnificent beat ! I wish to apprentice even as you amend your website, how can i subscribe for a weblog web site? The account aided me a acceptable deal. I had been tiny bit acquainted of this your broadcast provided vivid transparent idea 2019/05/09 7:51 Magnificent beat ! I wish to apprentice even as yo

Magnificent beat ! I wish to apprentice even as you amend your website, how can i subscribe for a weblog web site?
The account aided me a acceptable deal. I had been tiny
bit acquainted of this your broadcast provided vivid transparent idea

# Incredible points. Sound arguments. Keep up the amazing work. 2019/05/15 19:04 Incredible points. Sound arguments. Keep up the am

Incredible points. Sound arguments. Keep up the amazing work.

# all the time i used to read smaller posts that as well clear their motive, and that is also happening with this piece of writing which I am reading now. 2019/05/31 22:00 all the time i used to read smaller posts that as

all the time i used to read smaller posts that as well clear their motive, and that is also happening with this piece
of writing which I am reading now.

# Good replies in return of this issue with firm arguments and describing the whole thing about that. 2019/06/03 4:03 Good replies in return of this issue with firm arg

Good replies in return of this issue with firm arguments and describing the whole thing about that.

# Thanks for sharing such a fastidious thought, post is pleasant, thats why i have read it completely 2019/06/04 15:19 Thanks for sharing such a fastidious thought, post

Thanks for sharing such a fastidious thought, post is pleasant,
thats why i have read it completely

# Marvelous, what a web site it is! This blog gives helpful information to us, keep it up. 2019/06/05 3:05 Marvelous, what a web site it is! This blog gives

Marvelous, what a web site it is! This blog gives helpful information to us, keep it up.

# As the admin of this web site is working, no question very shortly it will be renowned, due to its feature contents. 2019/06/05 12:53 As the admin of this web site is working, no quest

As the admin of this web site is working, no question very shortly it will be renowned, due to its
feature contents.

# YlomZcMsnUW 2021/07/03 3:26 https://amzn.to/365xyVY

this I have discovered It absolutely useful and it has aided me out loads.

# lana rhoades video - https://lanarhoades.fun/ lana rhoades modeli
2024/03/02 21:12 Rhodess

lana rhoades video - https://lanarhoades.fun/ lana rhoades modeli

# lana rhoades full video - https://lanarhoades.pro/ lana rhoades pics
2024/03/06 13:40 LanaRho

lana rhoades full video - https://lanarhoades.pro/ lana rhoades pics

# aviator login: https://aviatorghana.pro/ play aviator
2024/03/12 6:30 AviatorGh

aviator login: https://aviatorghana.pro/ play aviator

# aviator bet https://aviatorjogar.online/ - jogar aviator Brasil
2024/03/12 17:16 BraAvia

aviator bet https://aviatorjogar.online/ - jogar aviator Brasil

タイトル  
名前  
Url
コメント