3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でMicrosoft.Extensions.DependencyInjectionを使用してDIをする

Last updated at Posted at 2023-01-10

1. はじめに

  • JavaでアノテーションをつけてDIするようにC#でも似たようなことをしたい
  • DIすることで単体テストをモックを使用してできるようにしたい
  • Microsoft製のDIコンテナ(Microsoft.Extensions.DependencyInjection)を使いたい

2. 開発環境

  • Visual Studio 2022
  • .NET6
  • Microsoft.Extensions.DependencyInjection (NuGet)
  • Windows11

3. Visual Studioで新規プロジェクトを作成する

  • 「コンソールアプリ」 を選択する
    image.png

  • ソリューション名/プロジェクト名は「DiConsoleApp」を設定する(任意)
    image.png

  • フレームワークは「.NET 6.0」を選択する
    image.png

4. Microsoft.Extensions.DependencyInjectionをインストールする

  • ソリューションエクスプローラから「依存関係」を右クリックして、「NuGetパッケージの管理」を選択する
  • 参照タブより「Microsoft.Extensions.DependencyInjection」をインストールする
    image.png

5. インターフェースを追加する

  • 新しい項目を追加で、「インターフェース」 を追加する
IMyService.cs
namespace DiConsoleApp
{
    public interface IMyService
    {
        public void getValue();
    }
}

5. クラスを追加する

  • 新しい項目を追加で、「クラス」 を追加する
MyService.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DiConsoleApp
{
    public class MyService : IMyService
    {
        public void getValue()
        {
            Debug.WriteLine("MyService コンストラクタ");
        }
    }
}

6. Program.csを修正する

Prcogram.cs
using DiConsoleApp;
using Microsoft.Extensions.DependencyInjection;
using System.Diagnostics;

namespace DiConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {

            // サービスコレクションを生成
            var collection = new ServiceCollection();

            // サービスコレクションにクラスと生成方法を登録
            // AddSingleton(): 最初にサービスコンテナから要求されたタイミングでインスタンスを生成
            // AddScoped(): クライアントから接続されたタイミングでインスタンスを生成
            // AddTransient(): サービスコンテナから要求されたタイミングでインスタンスを生成
            collection.AddTransient<IMyService, MyService>();

            // サービスプロバイダから型(IMyService)に対応するインスタンスを取得
            var provider = collection.BuildServiceProvider();
            var myService = provider.GetRequiredService<IMyService>();

            // メソッドを実行
            myService.getValue();
        }
    }
}

7. 動作確認

  • DIコンテナに登録したMyServiceのgetValue()が実行された
  • サンプルにはないが、クラスAはコンストラクタでBを必要とするような場合でもServiceProviderが適切に処理してくれる
    image.png

8. ソースコード

9. 参考文献

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?