かずきのBlog@hatena

すきな言語は C# + XAML の組み合わせ。Azure Functions も好き。最近は Go 言語勉強中。日本マイクロソフトで働いていますが、ここに書いていることは個人的なメモなので会社の公式見解ではありません。

Spring.NETのHello worldまでの道のり

まずは本家からダウンロード。
現時点の安定版の最新と思われる1.0.2をゲット。
zip版をダウンロードしたので、適当なところに解凍して置いといた。


次にコンソールアプリケーションのプロジェクトを作成する。
下の4つのdllを参照へ追加する。

  1. Spring.Core.dll
  2. Spring.Aop.dll
  3. log4net.dll
  4. antlr.runtime.dll

App.configをプロジェクトに追加したら下のような内容にする。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="spring">
            <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
            <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
        </sectionGroup>
    </configSections>
    <spring>
        <context>
            <resource uri="config://spring/objects"/>
        </context>

        <objects xmlns="http://www.springframework.net">
        </objects>
    </spring>
</configuration>

objectsタグにxmlnsタグが無いとApplicationContext作る時に例外がぶっとぶ。
これにはまった。

contextタグにはresourceタグで設定ファイルを追加していく。
ここでは、App.config内のものを直接指し示すようにしてある。


あとは、ハローワールドを残すのみ。
こんなクラスをでっちあげる。

namespace Sample
{
    class Greeter
    {
        private string message;

        public string Message
        {
            get { return message; }
            set { message = value; }
        }

        public void Execute() { Console.WriteLine(message); }
    }
}

App.configに追加。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <sectionGroup name="spring">
            <section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
            <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
        </sectionGroup>
    </configSections>
    <spring>
        <context>
            <resource uri="config://spring/objects"/>
        </context>

        <objects xmlns="http://www.springframework.net">
            <object name="greeter" type="Sample.Greeter">
                <property name="message">
                    <value>こんにちは世界</value>
                </property>
            </object>
        </objects>
    </spring>
</configuration>

あとは、MainにIApplicationContextをゲットするコードを書いて完成。

    class Program
    {
        static void Main(string[] args)
        {
            IApplicationContext ctx = ContextRegistry.GetContext();
            Greeter g = (Greeter)ctx.GetObject("greeter");
            g.Execute();
        }
    }

ポイントは、IApplicationContextをContextRegistryを使ってるところ。
App.configの設定がいきてるらしい。

実行結果は明らかなので省略。