public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
// Cách 1: GetValue
var maxItems = Configuration.GetValue<int>("AppSettings:MaxItemsPerPage", 10);
// Cách 2: GetSection
var appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
// Cách 3: Bind to object
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
}
}
// Model class
public class AppSettings
{
public int MaxItemsPerPage { get; set; } = 10;
public bool EnableCache { get; set; }
public EmailSettings Email { get; set; }
}
public class EmailSettings
{
public string SmtpHost { get; set; }
public int SmtpPort { get; set; }
}
// Đăng ký
builder.Services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
// Sử dụng
public class ProductService
{
private readonly AppSettings _settings;
public ProductService(IOptions<AppSettings> options)
{
_settings = options.Value;
}
public int GetPageSize() => _settings.MaxItemsPerPage;
}
// IOptions - Đọc config một lần khi app khởi động
// Singleton services nên dùng cái này
// IOptionsSnapshot - Đọc lại config mỗi request
// Scoped services nên dùng cái này để có config mới nhất
builder.Services.AddScoped<IOptionsSnapshot<AppSettings>>();
// IOptionsMonitor - Theo dõi thay đổi config real-time
// Dùng cho hot-reload configuration
builder.Services.AddSingleton<IOptionsMonitor<AppSettings>>();
// ✅ Correct
Log.Debug("Processing request {RequestId}", requestId);
Log.Information("Product {ProductId} created successfully", productId);
Log.Warning("Cache miss for key {CacheKey}", key);
Log.Error(ex, "Failed to process order {OrderId}", orderId);
Log.Fatal(ex, "Application terminating due to unhandled exception");