iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 13
1
Modern Web

.Net Core 網站開發 101系列 第 13

Configuration 組態設定 - 2/2

昨天說明了如何在應用程式中加入不同設定來源的組態設定,並取得設定值。實際的專案中,設定來源常常都是階層式架構,如果每次都要記得那麼長一串的 key 值真的是很麻煩!今天會說明怎麼把這些設定轉換成代表一組設定的類別,並透過依賴注入來取得這些設定。

繫結到類別

除了使用 GetValue<T> 方法來取得設定值,IConfiguration 也提供 Bind 擴充方法來建立 POCO 物件。

首先建立幾個類別來對應昨天的設定檔:

public class PersonnelProfile
{
    public string Name { get; set; }

    public Creations Creations { get; set; }
}

public class Creations
{
    public List<Blog> Blogs { get; set; }

    public List<Project> Projects { get; set; }
}

public class Blog
{
    public string Title { get; set; }
}

public class Project
{
    public string Name { get; set; }
}

昨天範例中的 JSON 設定檔:

{
  "profile": {
    "name": "Rex",  
    "creations": {
        "blogs": [{
            "title": ".NET Core 介紹",
        }, {
            "title": "常用 dotnet 命令介紹"
        }],
        "projects": [{
            "name": "ironman2018",
        }]
    }  
  },
}

會產生下列的 key-value 對應組合:

Key Value
profile:name Rex
profile:creations:blogs:0:title .NET Core 介紹
profile:creations:blogs:1:title 常用 dotnet 命令介紹
profile:creations:projects:0:name ironman2018

可以先呼叫 GetSection 取得 profile 的設定片段,再呼叫 Bind 方法轉換成對應的 PersonnelProfile 物件:

var personnelProfile = new PersonnelProfile();
_config.GetSection("profile").Bind(personnelProfile);

Options Pattern(選項模式)

我們也可以透過依賴注入的方式,將代表設定的物件先註冊到服務容器中,應用程式中要使用相關的設定時,再以注入 IOptions 的方式取得相關的設定物件。

public class ConfigurationController : Controller
{
    private readonly IOptions<PersonnelProfile> _optionsAccessor;

    public ConfigurationController(IConfiguration config, IOptions<PersonnelProfile> optionsAccessor)
    {
        _optionsAccessor = optionsAccessor;
    }

    public IActionResult Index()
    {
        var personnelProfile = _optionsAccessor.Value;

        return View(personnelProfile);
    }
}

直接傳入 IConfiguration 取值

services.Configure<PersonnelProfile>(_config.GetSection("profile"));

在註冊時設定值

services.Configure<PersonnelProfile>(profile =>
{
    profile.Name = "Registered in Startup.cs";
});

參考資料


上一篇
Configuration 組態設定 - 1/2
下一篇
Logging 日誌記錄
系列文
.Net Core 網站開發 10131
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言