
C#ASP.NET CoreOptions Pattern
6/3/2025
The Options Pattern is a design approach in ASP.NET Core that allows you to:
This leads to clean, modular, and testable configuration code.
Let's walk through a real example to see how it works.
GitHub Repo Example: SaifSaidi/OptionsPatternExample
appsettings.json
{
"MyAppSettings": {
"ApplicationName": "My App",
"Version": "1.0.0"
}
}
POCO
to Represent the Settingspublic class MyAppSettings
{
public string ApplicationName { get; set; }
public string Version { get; set; }
}
Program.cs
var builder = WebApplication.CreateBuilder(args);
// Bind the settings section to the POCO
builder.Services.Configure<MyAppSettings>(
builder.Configuration.GetSection("MyAppSettings"));
var app = builder.Build();
[ApiController]
public class HomeController : ControllerBase
{
private readonly MyAppSettings _settings;
public HomeController(IOptions<MyAppSettings> options)
{
_settings = options.Value;
}
[HttpGet]
[Route("api/home/settings")]
public IActionResult GetSettings()
{
return Ok(new
{
_settings.ApplicationName,
_settings.Version
});
}
}
builder.Services.AddOptions<MyAppSettings>()
.Bind(builder.Configuration.GetSection("MyAppSettings"))
.Validate(settings => !string.IsNullOrEmpty(settings.ApplicationName), "App name must be set")
.ValidateOnStart();
The Options Pattern in ASP.NET Core provides a powerful way to manage application settings. By binding configuration to strongly typed classes, you can create clean, maintainable, and testable code.
This pattern not only enhances the organization of your configuration but also leverages the benefits of dependency injection and validation, making your application more robust and easier to work with.