1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

サービスロケーターパターンの実装覚え書き

1
Last updated at Posted at 2026-01-04

1. 概要

大抵はDI( Microsoft.Extensions.DependencyInjection とか、Unity系だと VContainerZenject など)を導入してコーディングしているが、たまにサービスロケーターパターンを使用することもあるので、その時に使う実装を残しておく。

2. 実装

using System:

namespace NamePlaceholer
{
    /// <summary>
    /// 依存関係を解決するサービスロケーター.
    /// </summary>
    public static class ServiceLocator
    {
        // static type caching
        private static class Cache<T> where T : class
        {
            public static T Instance { get; set; }
        }

        /// <summary>
        /// インスタンスを登録する.
        /// </summary>
        /// <param name="instance">インスタンス.</param>
        /// <typeparam name="T">対象の型.</typeparam>
        public static void Register<T>(T instance) where T : class
        {
            Cache<T>.Instance ??= instance;
        }

        /// <summary>
        /// インスタンスを取得する(依存解決する).
        /// </summary>
        /// <typeparam name="T">対象の型.</typeparam>
        /// <returns>インスタンス.</returns>
        public static T Resolve<T>() where T : class
        {
            return Cache<T>.Instance ?? throw new InvalidOperationException($"Type {typeof(T).FullName} is not registered.");
        }
    }
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?