.NET6 以降の ASP.NET Core アプリケーションでIConfiguration オブジェクトを利用する - ASP.NET Core

.NET6 以降の ASP.NET Core アプリケーションでIConfiguration オブジェクトを利用するコードを紹介します。

概要

.NET5以前のASP.NET Core アプリケーションと .NET6以降のASP.NET Core アプリケーションでは、アプリケーション初期化部分のひな型コードが大きく変化し、 使用方法が異なるものがいくつかあります。この記事では、IConfiguration オブジェクトを.NET6以降のASP.NET Coreアプリケーションで利用するコードを紹介します。

利用方法

WebApplicationオブジェクト (app変数) のConfiguration プロパティがIConfiguration オブジェクトになります。

コード

.NET5 以前

.NET5 以前のASP.NET Core アプリケーションは以下の記述です。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
              webBuilder.UseStartup<Startup>();
            });
  }
}
Startup.cs (IConfiguration の利用あり)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace iPentecSampleApp
{
  public class Startup
  {
    private IConfiguration _config;

    public Startup(IConfiguration config)
    {
      _config = config;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
      }

      string setting_key = _config.GetSection("AppConfiguration")["SettingData"]; //IConfiguration を利用した設定ファイルの読み込み

      app.UseRouting();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapGet("/", async context =>
              {
            await context.Response.WriteAsync("Hello World!");
          });
      });
    }
  }
}

.NET5 以前では、IConfiguration オブジェクトにアクセスするには、Startup クラスのコンストラクタに、 IConfiguration オブジェクトのインジェクションの引数を追加し、IConfiguration オブジェクトをクラスのメンバ変数(上記コードでは _config 変数)に 代入して保持していました。
appsettings.jsonファイルからの情報の読み込みの場合には、保持した _configから GetSection() メソッドを呼び出し、設定ファイルから情報を読み込みます。

.NET6 以降

.NET6 以降のASP.NET Coreのコードは以下になります。
Program.cs (最上位レベルのステートメント(Top-level statements)を使用しない場合)
namespace iPentecSampleApp
{
  public class Program
  {
    public static void Main(string[] args)
    {
      var builder = WebApplication.CreateBuilder(args);
      var app = builder.Build();

      string setting_key = app.Configuration.GetSection("AppConfiguration")["SettingData"]; //Configuration を利用した設定ファイルの読み込み

      app.MapGet("/", () => "Hello World!");

      app.Run();
    }
  }
}

IConfiguration オブジェクトにアクセスするには、app変数(WebApplication オブジェクト)の Configuration プロパティにアクセスします。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2024-02-13
作成日: 2024-02-11
iPentec all rights reserverd.