preloader

關於Options Pattern

ASP.NET Core裡面有一項功能我覺得挺實用的稍為作筆記一下,ASP.NET Core的Options Pattern可以將組態資料繫結到【類別】,透過程式再去存取類別,使得程式不直接相依組態系統。
Option兩個條件狀況

  • 必須為非抽象類別
  • 建構函數必須為public且無參數

首先先透過appsetting.json的Developer區段設定值,不直接存取組態,而是透過Options選項模式讀取組態設定。

{
  "Developer": {
    "Name": "eddie",
    "Email": "eddie@gmail.com",
    "WebSite": "http://www.google.com.tw"

  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

建立DeveloperOption類別,三個屬性名稱與組態對應。 Options/DeveloperOptions.csharp

    public class DeveloperOptions
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string WebSite { get; set; }
    }

Startup.cs中註冊ConfigureServices註冊Options類別去對應組態設定。

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<DeveloperOptions>(o =>
            Configuration.GetSection("Developer").Bind(o));
           
            services.AddControllersWithViews();
        }

@using WebMVCDemo.Options;
@using Microsoft.Extensions.Options;
@inject IOptionsMonitor<DeveloperOptions> developerOptions

@{
    ViewData["Title"] = "Home Page";

    var devoptions = developerOptions.CurrentValue;
}



<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<ul>
    <li>
        Name:@devoptions.Name
    </li>
    <li>
        Email:@devoptions.Email
    </li>
    <li>
        WebSite:@devoptions.WebSite
    </li>
</ul>


comments powered by Disqus
comments powered by Disqus