青柳臣一 blog : .NET や C# がメインの blog

.NET や C# がメインの blog
投稿数 - 548, コメント - 259, トラックバック - 205

Web.config に IConfigurationSectionHandler を使って独自の設定項目を追加する

IConfigurationSectionHandler を使うと Web.Config に簡単に独自の設定を追加することができます。


MyConfig クラス
using System;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
 
namespace WebApplication1
{
    [Serializable]
    public class MyConfig : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, System.Xml.XmlNode section) 
        {
            XmlSerializer ser = new XmlSerializer(this.GetType());
            return ser.Deserialize(new XmlNodeReader(section));
        }
 
        public MyConfig()
        {
        }
 
        public static MyConfig Instance()
        {
            return (MyConfig)ConfigurationSettings.GetConfig("MyConfig");
        }
 
        private string _strParam = "*";        // default: "*"
        public string StrParam
        {
            get { return _strParam; }
            set { _strParam = value; }
        }
 
        private bool _boolParam = true;        // default: true
        public bool BoolParam
        {
            get { return _boolParam; }
            set { _boolParam = value; }
        }
 
        private int _intParam = 10;            // default: 10
        public int IntParam
        {
            get { return _intParam; }
            set { _intParam = value; }
        }
    }
}

Web.config
<configuration>
    <configSections>
        <section name="MyConfig" type="WebApplication1.MyConfig, WebApplication1"/>
    </configSections>
 
    <MyConfig>
        <StrParam>abc</StrParam>
        <BoolParam>false</BoolParam>
        <IntParam>5</IntParam>
    </MyConfig>
</configuration>

こういう風にしておくと読み込みの際に MyConfig.Create が呼ばれるので XmlSerializer を使ってデシリアライズしてあげるわけです。
使うときはこんな感じ

Label1.Text = MyConfig.Instance().StrParam;
Label2.Text = MyConfig.Instance().BoolParam.ToString();
Label2.Text = MyConfig.Instance().IntParam.ToString();
ちなみにデシリアライズされた結果はキャッシュされているようで MyConfig.Instance() するたびにデシリアライズが実行されるということはありません。
あと、たとえば int 型の項目に "abc" とかって指定するとデシリアライズ時に例外が発生するのでエラーページが表示されることになります。

投稿日時 : 2004年3月30日 11:02

トラックバックは下記のURLにpingを送信してください。
TrackBack URL: http://www.divakk.co.jp/blog/aoyagi/services/trackbacks/475.aspx

フィードバック

# re: Web.config に独自の設定項目を追加する

re: Web.config に独自の設定項目を追加する
2004/03/30 11:32 | 原水商店 (トラックバック)

# re: Web.config に IConfigurationSectionHandler を使って独自の設定項目を追加する

http://www.hollytown.net/uniblog/PermaLink.aspx?id=425c7067-48fe-4653-861e-546cc8bc0e8f

うちで使ってる構成セクションのHandler(.Textのものと同じ)に関するサンプルを書きました。
2004/04/20 19:49 | うに。

コメントの投稿

タイトル  
名前  
URL
コメント   
Protected by Clearscreen.SharpHIPこの絵に表示されている文字列を入力してください (半角で4文字です):