present@わんくま

本家はこちら

目次

Blog 利用状況

ニュース

アクセサリ

書庫

日記カテゴリ

ギャラリ

リンク

構成ファイルを記述して依存性を注入する

はじめに

先日はコードでの依存性注入を試したので、
今回は構成ファイルを使ったサンプルを作成してみました。
先日のサンプルが元になっています。

参照するアセンブリを追加

  • Microsoft.Practices.ObjectBuilder2
  • Microsoft.Pracitces.Unity

だけじゃなく

  • Microsoft.Practices.Unity.Configuration
  • System.Configuration

も追加。

Dependency 属性を修正

public class Person
{
    [Dependency]
    public IAnimal Pet { get; set; }

    // ペットを呼ぶ
    public void CallPet()
    {
        Pet.Cry();
    }
}

Dependency 属性で名前を指定するのをやめました。

構成ファイルを記述

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=1.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </configSections>
    <unity>
        <!--型の別名を定義-->
        <typeAliases>
            <typeAlias alias="IAnimal"
                       type="BuildUpSample.IAnimal, BuildUpSample"/>
            <typeAlias alias="Cat"
                       type="BuildUpSample.Cat, BuildUpSample"/>
            <typeAlias alias="Dog"
                       type="BuildUpSample.Dog, BuildUpSample"/>
        </typeAliases>
        
        <containers>
            <container name="Sample">
                <!--DI コンテナに登録する型を記述-->                
                <types>
                    <type type="IAnimal" mapTo="Dog"/>
                </types>
            </container>
        </containers>
    </unity>
</configuration>

typeAlias 要素で、型の別名を定義しています。
type 要素では別名を使って、型のマッピングを記述しています。

依存性を注入!

static void Main(string[] args)
{
    // DI コンテナを生成
    UnityContainer container = new UnityContainer();

    // 構成ファイルから unity セクションを読み込む
    UnityConfigurationSection section
        = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

    // 構成ファイルの内容を適用する
    section.Containers["Sample"].Configure(container);
    
    Person person = new Person();

    // 依存性を注入する
    person = container.BuildUp<Person>(person);

    // ペットを呼ぶ
    person.CallPet();

    Console.ReadLine();
}

このコードの実行結果は次の通り。

Dog クラスのインスタンスが注入されていますね。

構成ファイルを書き変えて見る

<type type="IAnimal" mapTo="Cat"/>

と書き変えて(再ビルドしないで)実行すると

と出力されます。
Cat クラスに切り替わりました。

別名を記述しなくてもいい

別名を記述せずに直接

<type type="BuildUpSample.IAnimal, BuildUpSample" mapTo="BuildUpSample.Cat, BuildUpSample"/>

と書いてもいいです。

まとめ

構成ファイルを書き変えるだけで呼び出すクラスを切り替えることができました。
でも構成ファイル(設定ファイル)は古いやり方みたい…。
現在の主流について調べないとなぁ~。

投稿日時 : 2008年11月2日 23:27

コメントを追加

# re: 構成ファイルを記述して依存性を注入する 2008/11/03 11:49 やじゅ

>構成ファイル(設定ファイル)は古いやり方みたい…
古いのか良く分かりませんが、GoogleのGuiceは、
設定ファイルではなくJavaクラスを使うようです。
http://gihyo.jp/dev/serial/01/awdp/000101

また、C#で設定ファイルではなくスクリプトを使ってる
サンプルを発見しましたw
http://d.hatena.ne.jp/akiramei/20080501

# re: 構成ファイルを記述して依存性を注入する 2008/11/04 10:17 なかむら

>GoogleのGuiceは、
設定ファイルではなくJavaクラスを使うようです。

情報ありがとうございます。
Guice っていう DI コンテナがあったんですね。
これは知らなかった…。

# GDMtxWaNxpWMWtHsj 2011/12/13 20:38 http://www.drinkershealth.net/antabuse-disulfiram/

Current blog, fresh information, I read it from time to time!!...

# ekAmlxBXqpTRqcjoBsL 2012/01/04 6:30 http://www.kosherbeefjerky.com/

vIlriO It's pleasant sitting at work to distract from it?to relax and read the information written here:D

# sildenafil citrate tablets 100 mg https://viasild24.online/
2021/12/07 19:18 Nyusjdh

sildenafil citrate tablets 100 mg https://viasild24.online/

# barinat https://baricitinibrx.com
baricitinib price
2021/12/12 16:21 Buksdldj

barinat https://baricitinibrx.com
baricitinib price

# bimatoprost generic best price https://bimatoprostrx.com
buy bimatoprost
2021/12/13 16:01 Hksfnjkh

bimatoprost generic best price https://bimatoprostrx.com
buy bimatoprost

# doxycycline generic https://doxycyline1st.com/
doxycycline 50 mg 2022/02/26 8:21 Jusidkid

doxycycline generic https://doxycyline1st.com/
doxycycline 50 mg

# where to purchase doxycycline https://doxycyline1st.com/
doxycycline hyc 2022/02/26 17:48 Jusidkid

where to purchase doxycycline https://doxycyline1st.com/
doxycycline hyc

# clomiphene for sale http://clomidus.store/ 2022/04/12 20:25 Clomids

clomiphene for sale http://clomidus.store/

# buying prednisone on line http://prednisoneen.store/ 2022/04/17 6:46 Prednisone

buying prednisone on line http://prednisoneen.store/

# furosemide 40mg https://buylasix.icu/
buy furosemide online 2022/06/25 1:05 LasixRx

furosemide 40mg https://buylasix.icu/
buy furosemide online

# anti-depressants https://allpharm.store/ 2022/07/22 5:59 AllPharm

anti-depressants https://allpharm.store/

# ivermectin guinea pig https://stromectolbestprice.com/ 2022/07/30 8:19 BestPrice

ivermectin guinea pig https://stromectolbestprice.com/

# prednisone 10mg buy online https://deltasone.icu/
mail order prednisone 2022/08/22 17:34 Prednisone

prednisone 10mg buy online https://deltasone.icu/
mail order prednisone

# new ed pills https://ed-pills.xyz/
online ed pills 2022/09/17 2:55 EdPills

new ed pills https://ed-pills.xyz/
online ed pills

# cheap antibiotic https://antibiotic.best/ 2022/10/08 8:52 Antibiotic

cheap antibiotic https://antibiotic.best/

#  https://clomidforsale.site/ 2022/11/13 21:19 ForSale

https://clomidforsale.site/

# treatment of ed https://cheapestedpills.com/
best otc ed pills 2022/12/10 22:14 CheapPills

treatment of ed https://cheapestedpills.com/
best otc ed pills

# earch our drug database. drug information and news for professionals and consumers.
https://canadianfast.com/
Read now. Best and news about drug. 2023/02/19 12:51 CanadaBest

earch our drug database. drug information and news for professionals and consumers.
https://canadianfast.com/
Read now. Best and news about drug.

# buy doxycycline - https://doxycyclinesale.pro/# 2023/04/21 23:21 Doxycycline

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

# prednisone without rx - https://prednisonesale.pro/# 2023/04/22 10:31 Prednisone

prednisone without rx - https://prednisonesale.pro/#

# Cytotec 200mcg price - https://cytotecsale.pro/# 2023/04/29 6:30 Cytotec

Cytotec 200mcg price - https://cytotecsale.pro/#

# reputable mexican pharmacies https://pillswithoutprescription.pro/# 2023/05/16 11:32 PillsPro

reputable mexican pharmacies https://pillswithoutprescription.pro/#

# buy paxlovid online https://paxlovid.pro/# - Paxlovid buy online 2023/07/02 23:12 Paxlovid

buy paxlovid online https://paxlovid.pro/# - Paxlovid buy online

# ed pill https://edpillsotc.store/# - medications for ed 2023/10/08 2:50 EdPills

ed pill https://edpillsotc.store/# - medications for ed

タイトル
名前
URL
コメント