Dotnet Core Webアプリを使ってDIを勉強する

Dotnet Core WebアプリでDI(Dependency Injection)を勉強する。
今回は、以下をターゲットとする。
  • appsettings.jsonを使ったDI
  • Controllerで利用

作成、修正するファイル
  • appsettings.json
  • Models/AppSettings.cs(新規作成)
  • Startup.cs
  • Controllers/HomeControllers

0. Dotnet Core Webアプリプロジェクトを作成する
VisualStudioのファイル→新規作成→プロジェクト
→ASP.NET Core Webアプリケーションを選択。












次に、Webアプリケーション(モデルビューコントローラー)を選択。













これでプロジェクトが作成される。
このプロジェクトに以下の修正を加える。
1. appsettings.json
DIしたいデータを作成する。appsettings.jsonのデータを次のAppSettingsへInjectionする。
{
  "TestUpdateData": {
    "EndPointUrl": "http://localhost:8080",
    "AuthorizationKey": "12345678"
  },
  "AllowedHosts": "*"
}

2. Models/AppSettings.cs(新規作成)
上記で作成したjsonデータをここにInjectionする。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication4.Models
{
    public class AppSettings
    {
        public TestDB TestUpdateData { get; set; }
    }

    public class TestDB
    {
        public string EndPointUrl { get; set; }
        public string AuthorizationKey { get; set; }
    }
}

3. Startup.cs
services.AddMvc()、services.Configure(Configuration)を追加すると、強制的に
using WebApplication4.Models;
の挿入を求められる。
そして、ModelsのTestDBへInjectionされるらしい。素晴らしい簡単さだ。
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApplication4.Models;

namespace WebApplication4
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure(Configuration);
            services.AddControllersWithViews();
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

3. Controllers/HomeControllers
InjectionされたModelsのデータをControllerで受け取る手段を追加する。
コンストラクタにIOptions<AppSettings> optionsAccessorを追加してそこからデータを取得する。
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WebApplication4.Models;

namespace WebApplication4.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger logger;
        private readonly AppSettings appSettings;

        public HomeController(IOptions optionsAccessor, ILogger logger)
        {
            this.appSettings = optionsAccessor.Value;
            this.logger = logger;
        }

        public IActionResult Index()
        {
            // INFO レベルでログを出力.
            logger.Log(LogLevel.Information, ("I:TestUpdateData: EndPointUrl : " + this.appSettings.TestUpdateData.EndPointUrl));
            logger.Log(LogLevel.Information, ("I:TestUpdateData: AuthorizationKey: " + this.appSettings.TestUpdateData.AuthorizationKey));
            logger.Log(LogLevel.Debug, ("D:TestUpdateData: EndPointUrl : " + this.appSettings.TestUpdateData.EndPointUrl));
            logger.Log(LogLevel.Debug, ("D:TestUpdateData: AuthorizationKey: " + this.appSettings.TestUpdateData.AuthorizationKey));

            logger.LogDebug("--TestUpdateData: EndPointUrl : " + this.appSettings.TestUpdateData.EndPointUrl);
            logger.LogDebug("--TestUpdateData: AuthorizationKey: " + this.appSettings.TestUpdateData.AuthorizationKey);
           
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}

コメント

このブログの人気の投稿

ソリューション構成ごとにconfigファイルを作成する

C++の古いプロジェクトのビルドでerror MIDL2311 : statements outside library block are illegal in mktyplib compatability mode

web.config debug/releaseの内容を変換構文を使って切り替える