ASP.NET Core でのコントローラーへの依存関係の挿入

作成者: Shadi Namrouti および Rick Anderson

ASP.NET Core の MVC コントローラーは、コンストラクターを使用して明示的に依存関係を要求します。 ASP.NET Core には、依存関係の挿入 (DI) の組み込みのサポートがあります。 DI を利用すれば、アプリのテストと保守管理が簡単になります。

サンプル コードを表示またはダウンロードします (ダウンロード方法)。

コンストラクターの挿入

サービスはコンストラクター パラメーターとして追加されます。ランタイムによって、サービス コンテナーからサービスが解決されます。 サービスは通常、インターフェイスを利用して定義されます。 たとえば、現在の時刻を必要とするアプリについて考えてください。 次のインターフェイスは IDateTime サービスを公開します。

public interface IDateTime
{
    DateTime Now { get; }
}

次のコードは IDateTime インターフェイスを実装します。

public class SystemDateTime : IDateTime
{
    public DateTime Now
    {
        get { return DateTime.Now; }
    }
}

サービスをサービス コンテナーに追加します。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDateTime, SystemDateTime>();

    services.AddControllersWithViews();
}

AddSingleton の詳細については、DI のサービス有効期間に関するページを参照してください。

次のコードでは、一日の時刻に基づいてユーザーにあいさつが表示されます。

public class HomeController : Controller
{
    private readonly IDateTime _dateTime;

    public HomeController(IDateTime dateTime)
    {
        _dateTime = dateTime;
    }

    public IActionResult Index()
    {
        var serverTime = _dateTime.Now;
        if (serverTime.Hour < 12)
        {
            ViewData["Message"] = "It's morning here - Good Morning!";
        }
        else if (serverTime.Hour < 17)
        {
            ViewData["Message"] = "It's afternoon here - Good Afternoon!";
        }
        else
        {
            ViewData["Message"] = "It's evening here - Good Evening!";
        }
        return View();
    }

アプリを実行すると、時刻に基づいてメッセージが表示されます。

FromServices を使用したアクションの挿入

FromServicesAttribute を利用すると、コンストラクター挿入を利用しなくても、アクション メソッドがサービスに直接挿入されます。

public IActionResult About([FromServices] IDateTime dateTime)
{
    return Content( $"Current server time: {dateTime.Now}");
}

FromKeyedServices を使用したアクションの挿入

次のコードは、[FromKeyedServices] 属性を使用して DI コンテナーからキー付きサービスにアクセスする方法を示しています。

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddKeyedSingleton<ICache, BigCache>("big");
builder.Services.AddKeyedSingleton<ICache, SmallCache>("small");
builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();

app.Run();

public interface ICache
{
    object Get(string key);
}
public class BigCache : ICache
{
    public object Get(string key) => $"Resolving {key} from big cache.";
}

public class SmallCache : ICache
{
    public object Get(string key) => $"Resolving {key} from small cache.";
}

[ApiController]
[Route("/cache")]
public class CustomServicesApiController : Controller
{
    [HttpGet("big")]
    public ActionResult<object> GetBigCache([FromKeyedServices("big")] ICache cache)
    {
        return cache.Get("data-mvc");
    }

    [HttpGet("small")]
    public ActionResult<object> GetSmallCache([FromKeyedServices("small")] ICache cache)
    {
        return cache.Get("data-mvc");
    }
}

コントローラーから設定にアクセスする

コントローラー内からアプリまたは構成の設定にアクセスするのが一般的なパターンです。 ASP.NET Core のオプション パターン で説明されているオプション パターンが設定の管理手法として推奨されています。 通常はコントローラーに IConfiguration を直接挿入しないでください。

オプションを表すクラスを作成します。 次に例を示します。

public class SampleWebSettings
{
    public string Title { get; set; }
    public int Updates { get; set; }
}

サービス コレクションに構成クラスを追加します。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDateTime, SystemDateTime>();
    services.Configure<SampleWebSettings>(Configuration);

    services.AddControllersWithViews();
}

JSON 形式ファイルから設定を読み込むようにアプリを構成します:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("samplewebsettings.json",
                    optional: false,
                    reloadOnChange: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

次のコードはサービス コンテナーから IOptions<SampleWebSettings> 設定を要求し、それを Index メソッドで使用します。

public class SettingsController : Controller
{
    private readonly SampleWebSettings _settings;

    public SettingsController(IOptions<SampleWebSettings> settingsOptions)
    {
        _settings = settingsOptions.Value;
    }

    public IActionResult Index()
    {
        ViewData["Title"] = _settings.Title;
        ViewData["Updates"] = _settings.Updates;
        return View();
    }
}

その他のリソース

作成者: Shadi NamroutiRick AndersonSteve Smith

ASP.NET Core の MVC コントローラーは、コンストラクターを使用して明示的に依存関係を要求します。 ASP.NET Core には、依存関係の挿入 (DI) の組み込みのサポートがあります。 DI を利用すれば、アプリのテストと保守管理が簡単になります。

サンプル コードを表示またはダウンロードします (ダウンロード方法)。

コンストラクターの挿入

サービスはコンストラクター パラメーターとして追加されます。ランタイムによって、サービス コンテナーからサービスが解決されます。 サービスは通常、インターフェイスを利用して定義されます。 たとえば、現在の時刻を必要とするアプリについて考えてください。 次のインターフェイスは IDateTime サービスを公開します。

public interface IDateTime
{
    DateTime Now { get; }
}

次のコードは IDateTime インターフェイスを実装します。

public class SystemDateTime : IDateTime
{
    public DateTime Now
    {
        get { return DateTime.Now; }
    }
}

サービスをサービス コンテナーに追加します。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDateTime, SystemDateTime>();

    services.AddControllersWithViews();
}

AddSingleton の詳細については、DI のサービス有効期間に関するページを参照してください。

次のコードでは、一日の時刻に基づいてユーザーにあいさつが表示されます。

public class HomeController : Controller
{
    private readonly IDateTime _dateTime;

    public HomeController(IDateTime dateTime)
    {
        _dateTime = dateTime;
    }

    public IActionResult Index()
    {
        var serverTime = _dateTime.Now;
        if (serverTime.Hour < 12)
        {
            ViewData["Message"] = "It's morning here - Good Morning!";
        }
        else if (serverTime.Hour < 17)
        {
            ViewData["Message"] = "It's afternoon here - Good Afternoon!";
        }
        else
        {
            ViewData["Message"] = "It's evening here - Good Evening!";
        }
        return View();
    }

アプリを実行すると、時刻に基づいてメッセージが表示されます。

FromServices を使用したアクションの挿入

FromServicesAttribute を利用すると、コンストラクター挿入を利用しなくても、アクション メソッドがサービスに直接挿入されます。

public IActionResult About([FromServices] IDateTime dateTime)
{
    return Content( $"Current server time: {dateTime.Now}");
}

コントローラーから設定にアクセスする

コントローラー内からアプリまたは構成の設定にアクセスするのが一般的なパターンです。 ASP.NET Core のオプション パターン で説明されているオプション パターンが設定の管理手法として推奨されています。 通常はコントローラーに IConfiguration を直接挿入しないでください。

オプションを表すクラスを作成します。 次に例を示します。

public class SampleWebSettings
{
    public string Title { get; set; }
    public int Updates { get; set; }
}

サービス コレクションに構成クラスを追加します。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDateTime, SystemDateTime>();
    services.Configure<SampleWebSettings>(Configuration);

    services.AddControllersWithViews();
}

JSON 形式ファイルから設定を読み込むようにアプリを構成します:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("samplewebsettings.json",
                    optional: false,
                    reloadOnChange: true);
            })
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

次のコードはサービス コンテナーから IOptions<SampleWebSettings> 設定を要求し、それを Index メソッドで使用します。

public class SettingsController : Controller
{
    private readonly SampleWebSettings _settings;

    public SettingsController(IOptions<SampleWebSettings> settingsOptions)
    {
        _settings = settingsOptions.Value;
    }

    public IActionResult Index()
    {
        ViewData["Title"] = _settings.Title;
        ViewData["Updates"] = _settings.Updates;
        return View();
    }
}

その他のリソース

作成者: Shadi NamroutiRick AndersonSteve Smith

ASP.NET Core の MVC コントローラーは、コンストラクターを使用して明示的に依存関係を要求します。 ASP.NET Core には、依存関係の挿入 (DI) の組み込みのサポートがあります。 DI を利用すれば、アプリのテストと保守管理が簡単になります。

サンプル コードを表示またはダウンロードします (ダウンロード方法)。

コンストラクターの挿入

サービスはコンストラクター パラメーターとして追加されます。ランタイムによって、サービス コンテナーからサービスが解決されます。 サービスは通常、インターフェイスを利用して定義されます。 たとえば、現在の時刻を必要とするアプリについて考えてください。 次のインターフェイスは IDateTime サービスを公開します。

public interface IDateTime
{
    DateTime Now { get; }
}

次のコードは IDateTime インターフェイスを実装します。

public class SystemDateTime : IDateTime
{
    public DateTime Now
    {
        get { return DateTime.Now; }
    }
}

サービスをサービス コンテナーに追加します。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDateTime, SystemDateTime>();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

AddSingleton の詳細については、DI のサービス有効期間に関するページを参照してください。

次のコードでは、一日の時刻に基づいてユーザーにあいさつが表示されます。

public class HomeController : Controller
{
    private readonly IDateTime _dateTime;

    public HomeController(IDateTime dateTime)
    {
        _dateTime = dateTime;
    }

    public IActionResult Index()
    {
        var serverTime = _dateTime.Now;
        if (serverTime.Hour < 12)
        {
            ViewData["Message"] = "It's morning here - Good Morning!";
        }
        else if (serverTime.Hour < 17)
        {
            ViewData["Message"] = "It's afternoon here - Good Afternoon!";
        }
        else
        {
            ViewData["Message"] = "It's evening here - Good Evening!";
        }
        return View();
    }

アプリを実行すると、時刻に基づいてメッセージが表示されます。

FromServices を使用したアクションの挿入

FromServicesAttribute を利用すると、コンストラクター挿入を利用しなくても、アクション メソッドがサービスに直接挿入されます。

public IActionResult About([FromServices] IDateTime dateTime)
{
    ViewData["Message"] = $"Current server time: {dateTime.Now}";

    return View();
}

コントローラーから設定にアクセスする

コントローラー内からアプリまたは構成の設定にアクセスするのが一般的なパターンです。 ASP.NET Core のオプション パターン で説明されているオプション パターンが設定の管理手法として推奨されています。 通常はコントローラーに IConfiguration を直接挿入しないでください。

オプションを表すクラスを作成します。 次に例を示します。

public class SampleWebSettings
{
    public string Title { get; set; }
    public int Updates { get; set; }
}

サービス コレクションに構成クラスを追加します。

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IDateTime, SystemDateTime>();
    services.Configure<SampleWebSettings>(Configuration);
    
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

JSON 形式ファイルから設定を読み込むようにアプリを構成します:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
        {
            config.AddJsonFile("samplewebsettings.json", 
                                optional: false,        // File is not optional.
                                reloadOnChange: false);
        })
        .UseStartup<Startup>();
}

次のコードはサービス コンテナーから IOptions<SampleWebSettings> 設定を要求し、それを Index メソッドで使用します。

public class SettingsController : Controller
{
    private readonly SampleWebSettings _settings;

    public SettingsController(IOptions<SampleWebSettings> settingsOptions)
    {
        _settings = settingsOptions.Value;
    }

    public IActionResult Index()
    {
        ViewData["Title"] = _settings.Title;
        ViewData["Updates"] = _settings.Updates;
        return View();
    }
}

その他のリソース