0Pricing
C# Academy · บทเรียน

แหล่งและผู้ให้บริการการกำหนดค่า

แบ่งชั้นการกำหนดค่าจากไฟล์ JSON ตัวแปรสภาพแวดล้อม อาร์กิวเมนต์บรรทัดคำสั่ง และผู้ให้บริการแบบกำหนดเองตามลำดับความสำคัญ

แหล่งและผู้ให้บริการการกำหนดค่า เป็นบทเรียน C# Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน C# Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส C# Academy มีบทเรียนทั้งหมด 4 บทเรียน

การกำหนดค่าใน .NET

ระบบการกำหนดค่าของ ASP.NET Core อ่านการตั้งค่าจากหลายแหล่ง ได้แก่ ไฟล์ JSON ตัวแปรสภาพแวดล้อม อาร์กิวเมนต์บรรทัดคำสั่ง และอื่น ๆ แล้วผสานรวมเป็นที่เก็บคู่คีย์-ค่าแบบแบนชุดเดียว ซึ่งเข้าถึงได้จากทุกที่ใน app ของคุณ

appsettings.json

appsettings.json คือไฟล์การกำหนดค่าเริ่มต้น โดย Host.CreateApplicationBuilder จะโหลดไฟล์นี้โดยอัตโนมัติ การตั้งค่าจะถูกรวมเข้ากับค่าที่เขียนทับตามสภาพแวดล้อม

// appsettings.json
{
  "App": {
    "Name": "OrderService",
    "MaxRetries": 3
  },
  "ConnectionStrings": {
    "Default": "Server=localhost;Database=orders"
  }
}

// appsettings.Production.json overrides the above:
{
  "ConnectionStrings": {
    "Default": "Server=prod-db;Database=orders;..."
  }
}

การอ่านค่าการกำหนดค่า

เข้าถึงการกำหนดค่าผ่าน IConfiguration คีย์ใช้เครื่องหมายโคลอนสำหรับออบเจ็กต์ที่ซ้อนกัน ส่วนอาร์เรย์จะเข้าถึงด้วยดัชนี

// Inject IConfiguration
public class OrderService
{
    private readonly IConfiguration _config;

    public OrderService(IConfiguration cfg) => _config = cfg;

    public void Configure()
    {
        string? name     = _config["App:Name"];           // "OrderService"
        int maxRetries   = _config.GetValue<int>("App:MaxRetries"); // 3
        string? connStr  = _config.GetConnectionString("Default");

        // Nested section
        var section = _config.GetSection("App");
        string? appName = section["Name"];
    }
}

ตัวแปรสภาพแวดล้อม

ตัวแปรสภาพแวดล้อมจะเขียนทับการตั้งค่า JSON และจำเป็นอย่างยิ่งสำหรับการนำไปใช้งานในคอนเทนเนอร์ ขีดล่างคู่ (__) ใช้แทนตัวคั่นโคลอนในคีย์ที่ซ้อนกัน

# Set via shell or docker-compose:
export App__Name="OrderService-Prod"
export App__MaxRetries=5
export ConnectionStrings__Default="Server=prod-db;..."

// Equivalent to:
{
  "App": { "Name": "OrderService-Prod", "MaxRetries": 5 },
  "ConnectionStrings": { "Default": "Server=prod-db;..." }
}

// Priority: env vars > appsettings.{Environment}.json > appsettings.json

อาร์กิวเมนต์บรรทัดคำสั่ง

โดยค่าเริ่มต้น อาร์กิวเมนต์บรรทัดคำสั่งมีลำดับความสำคัญสูงสุด โดยใช้ไวยากรณ์ --key=value หรือ --key value และใช้โคลอนหรือขีดล่างคู่สำหรับการซ้อนระดับ

# Override config when launching the app:
dotnet run --App:Name="CLI-Override" --App:MaxRetries=10

# Or:
dotnet run --App__Name="CLI-Override"

// The builder.Configuration.AddCommandLine() is called
// automatically by Host.CreateApplicationBuilder().

// Priority order (highest to lowest):
// 1. Command-line args
// 2. Environment variables
// 3. appsettings.{ASPNETCORE_ENVIRONMENT}.json
// 4. appsettings.json

ข้อมูลลับของผู้ใช้

ข้อมูลลับของผู้ใช้ใช้จัดเก็บข้อมูลการกำหนดค่าที่มีความละเอียดอ่อนนอกไดเรกทอรีโครงการระหว่างการพัฒนา ข้อมูลเหล่านี้จะไม่ถูกส่งเข้าไปในระบบควบคุมซอร์สโค้ด และจะเขียนทับ appsettings.json ในเครื่อง

# Initialize user secrets for the project:
dotnet user-secrets init

# Set a secret:
dotnet user-secrets set "Database:Password" "SuperSecret123"
dotnet user-secrets set "Jwt:SecretKey" "dev-only-key"

# List secrets:
dotnet user-secrets list

# Remove:
dotnet user-secrets remove "Database:Password"

# Stored in: ~/.microsoft/usersecrets/{projectId}/secrets.json
# Automatically loaded in Development environment only

ผู้ให้บริการการกำหนดค่าแบบกำหนดเอง

นำ IConfigurationProvider และ IConfigurationSource ไปใช้งานเพื่อโหลดการกำหนดค่าจากแหล่งใดก็ได้ เช่น ฐานข้อมูล Consul Vault Redis และอื่น ๆ

public class DbConfigProvider : ConfigurationProvider
{
    private readonly string _connStr;
    public DbConfigProvider(string connStr) => _connStr = connStr;

    public override void Load()
    {
        using var conn = new NpgsqlConnection(_connStr);
        conn.Open();
        using var cmd = new NpgsqlCommand(
            "SELECT key, value FROM app_config", conn);
        using var reader = cmd.ExecuteReader();
        while (reader.Read())
            Data[reader.GetString(0)] = reader.GetString(1);
    }
}

public class DbConfigSource : IConfigurationSource
{
    private readonly string _connStr;
    public DbConfigSource(string connStr) => _connStr = connStr;
    public IConfigurationProvider Build(IConfigurationBuilder b)
        => new DbConfigProvider(_connStr);
}

การลงทะเบียนผู้ให้บริการแบบกำหนดเอง

เพิ่มแหล่งการกำหนดค่าแบบกำหนดเองลงใน builder ก่อนเรียกใช้ Build() แหล่งนี้จะเข้าไปอยู่ในลำดับความสำคัญเดียวกับผู้ให้บริการที่มีมาให้ในระบบ

var builder = Host.CreateApplicationBuilder(args);

// Add custom DB config provider after appsettings.json
builder.Configuration.Add(
    new DbConfigSource(
        builder.Configuration.GetConnectionString("Default")!));

// Or as an extension method:
public static class ConfigExtensions
{
    public static IConfigurationBuilder AddDatabaseConfig(
        this IConfigurationBuilder b, string connStr)
        => b.Add(new DbConfigSource(connStr));
}

// Usage:
builder.Configuration.AddDatabaseConfig(connStr);

การกำหนดค่า Azure App Configuration

Azure App Configuration รวมศูนย์การตั้งค่าระหว่างไมโครเซอร์วิสด้วยแฟล็กฟีเจอร์ ป้ายกำกับ และการกำหนดเวอร์ชัน ผู้ให้บริการอย่างเป็นทางการจะผสานรวมเข้ากับระบบในฐานะแหล่งการกำหนดค่ามาตรฐาน

// dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets
// dotnet add package Microsoft.Azure.AppConfiguration.AspNetCore

builder.Configuration.AddAzureAppConfiguration(options =>
    options
        .Connect(builder.Configuration["AzureAppConfig:ConnectionString"])
        .Select(KeyFilter.Any)                 // all keys
        .Select(KeyFilter.Any, "Production")   // label override
        .UseFeatureFlags(ff =>
            ff.CacheExpirationInterval = TimeSpan.FromMinutes(5))
        .ConfigureRefresh(r =>
            r.Register("App:Version", refreshAll: true)
             .SetCacheExpiration(TimeSpan.FromMinutes(1)))
);

app.UseAzureAppConfiguration(); // enable dynamic refresh

การโหลดการกำหนดค่าใหม่

ผู้ให้บริการบางรายรองรับการตรวจจับการเปลี่ยนแปลง ผู้ให้บริการ JSON สามารถโหลดใหม่ได้เมื่อไฟล์มีการเปลี่ยนแปลง ใช้ IOptionsMonitor<T> เพื่อตอบสนองต่อการเปลี่ยนแปลงขณะทำงาน

// Enable JSON file reload on change:
builder.Configuration.AddJsonFile("appsettings.json",
    optional: false, reloadOnChange: true);

// In a service, use IOptionsMonitor (not IOptions) to get live values:
public class FeatureService
{
    private readonly IOptionsMonitor<FeatureFlags> _monitor;

    public FeatureService(IOptionsMonitor<FeatureFlags> m) => _monitor = m;

    public bool IsBetaEnabled
        => _monitor.CurrentValue.BetaEnabled; // always fresh

    // React to changes:
    public FeatureService(IOptionsMonitor<FeatureFlags> m)
    {
        _monitor = m;
        m.OnChange(flags => Console.WriteLine("Config changed!"));
    }
}

ตรวจสอบความเข้าใจ

ควรใช้ตัวคั่นใดเพื่อแทนคีย์การกำหนดค่า JSON ที่ซ้อนกันเมื่อใช้เป็นตัวแปรสภาพแวดล้อม

กรณีใช้งานจริง: การกำหนดค่าจากหลายแหล่ง

ตัวอย่างการตั้งค่าสำหรับใช้งานจริงที่รวม appsettings ตัวแปรสภาพแวดล้อม และข้อมูลลับของผู้ใช้เข้าด้วยกัน พร้อมกำหนดลำดับความสำคัญอย่างชัดเจน

var builder = Host.CreateApplicationBuilder(args);

// Default: appsettings.json → appsettings.{env}.json → env vars → CLI
// Add user secrets in development:
if (builder.Environment.IsDevelopment())
    builder.Configuration.AddUserSecrets<Program>();

// Optionally add Azure Key Vault in production:
if (!builder.Environment.IsDevelopment())
{
    var keyVaultUri = builder.Configuration["Azure:KeyVaultUri"]!;
    builder.Configuration.AddAzureKeyVault(
        new Uri(keyVaultUri), new DefaultAzureCredential());
}

// Now all secrets are available transparently via IConfiguration
var jwtKey = builder.Configuration["Jwt:SecretKey"]!;

สรุปทบทวน: แหล่งการกำหนดค่าและผู้ให้บริการ

ประเด็นสำคัญ:

  • การกำหนดค่าจะถูกรวมจากหลายแหล่ง โดยแหล่งที่มาทีหลังจะเขียนทับแหล่งที่มาก่อน
  • ลำดับความสำคัญ: อาร์กิวเมนต์ CLI > ตัวแปรสภาพแวดล้อม > appsettings.{env}.json > appsettings.json
  • ใช้ __ (ขีดล่างคู่) ในตัวแปรสภาพแวดล้อมสำหรับคีย์ที่ซ้อนกัน
  • ข้อมูลลับของผู้ใช้ช่วยเก็บข้อมูลเข้าสู่ระบบสำหรับการพัฒนาไว้นอกระบบควบคุมซอร์สโค้ด
  • ผู้ให้บริการแบบกำหนดเอง: นำ IConfigurationSource + IConfigurationProvider ไปใช้งาน
  • ใช้ reloadOnChange: true + IOptionsMonitor เพื่ออัปเดตการกำหนดค่าแบบทันที

คำถามที่พบบ่อย

บทเรียน “แหล่งและผู้ให้บริการการกำหนดค่า” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “แหล่งและผู้ให้บริการการกำหนดค่า” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส C# Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส C# Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “แหล่งและผู้ให้บริการการกำหนดค่า”

แบ่งชั้นการกำหนดค่าจากไฟล์ JSON ตัวแปรสภาพแวดล้อม อาร์กิวเมนต์บรรทัดคำสั่ง และผู้ให้บริการแบบกำหนดเองตามลำดับความสำคัญ คุณปฏิบัติ C# Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน C# Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน C# Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “แหล่งและผู้ให้บริการการกำหนดค่า” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน C# Academy นี้ได้ไหม

ได้ บทเรียน C# Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. แหล่งและผู้ให้บริการการกำหนดค่า
  2. Options แบบระบุชนิดอย่างเคร่งครัดด้วย IOptions
  3. การตรวจสอบ Options และ Named Options
  4. การจัดการข้อมูลลับ
← กลับไปที่ C# Academy