Spring.NET を用いた属性ベースの依存性注入の実装方法

Spring.NET は Java の Spring フレームワークを .NET 向けに移植したオープンソースフレームワークであり、主な機能として以下のモジュールが含まれる:

  • 依存性注入(DI)
  • アスペクト指向プログラミング(AOP)
  • データアクセス抽象化
  • ASP.NET 拡張機能

本記事では、特に依存性注入機能に焦点を当て、属性注入による実装手順を解説する。

プロジェクト構成と前提

DAL(データアクセス層)、BLL(ビジネスロジック層)、Web 層の全体構造については省略し、Spring.NET および MyBatis の設定と連携に絞って説明する。開発を始める前に、必要なアセンブリ(例:Spring.Core、Spring.Web など)を公式サイトから取得し、プロジェクトに参照追加することを推奨する。

重要な設定ファイルは以下の通り:

  • Res/Objects/BLLObjects.xml:Spring.NET によるオブジェクト定義とプロパティ注入の設定
  • Web.config:Spring.NET の基本設定とリソースファイルの読み込みパス指定

Spring.NET の設定手順

1. Web.config での基本設定

まず、Spring.NET の設定セクションを登録する:

<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>
</configuration>

2. ASPX ページへの DI サポート追加

ページレベルでの依存性注入を有効にするため、system.web セクションに以下を追加する:

<system.web>
  <httpHandlers>
    <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web" />
  </httpHandlers>
  <httpModules>
    <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web" />
  </httpModules>
</system.web>

3. オブジェクト定義ファイルの読み込み

Spring コンテキストで使用する XML 設定ファイルを指定する。本例では相対パスを使用している:

<spring>
  <context>
    <resource uri="~/Res/Objects/BLLObjects.xml" />
    <resource uri="~/Res/Objects/DALObjects.xml" />
    <resource uri="~/Res/Objects/DBConfig.xml" />
  </context>
  <objects xmlns="http://www.springframework.net"></objects>
</spring>

4. オブジェクト定義(BLLObjects.xml)

以下はビジネスロジッククラスとその依存関係を定義する例である:

<?xml version="1.0" encoding="utf-8"?>
<objects xmlns="http://www.springframework.net">
  <object id="ArticleCategoryService" type="MyBlog.BLL.ArticleCategoryService, MyBlog.BLL">
    <property name="CategoryRepository" ref="CategoryDao" />
  </object>

  <object id="LogService" type="MyBlog.BLL.LogService, MyBlog.BLL">
    <property name="LogRepository" ref="LogDao" />
  </object>
</objects>

<object> 要素は C# クラスに対応し、id は一意の識別子、type は「完全修飾クラス名, アセンブリ名」の形式で指定する。<property> 要素により、プロパティへの依存オブジェクト(他の objectid)を注入する。

5. C# コードでの実装

以下は属性注入を受けるビジネスクラスの例である:

using MyBlog.IDAL;
using MyBlog.Model;
using System.Collections.Generic;

namespace MyBlog.BLL
{
    public class ArticleCategoryService
    {
        public ICategoryDao CategoryRepository { get; set; }

        public bool AddCategory(ArticleCategory category)
        {
            category.CategoryName += " [BLL 経由で追加]";
            return CategoryRepository.Insert(category);
        }

        public IList<ArticleCategory> GetAllCategories()
        {
            return CategoryRepository.SelectAll();
        }
    }
}

このクラスの CategoryRepository プロパティは、Spring.NET によって自動的に CategoryDao のインスタンスで初期化される。

タグ: Spring.NET Dependency Injection C# ASP.NET MyBatis

8月15日 14:09 投稿