Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Asp.Net Core

Options Pattern in ASP.NET Core: Configuration Magic for Robust Apps

- 22.08.26 | 22.08.26 - ErcanOPAK

🎯 Key Takeaways: Clean, type-safe configuration binding with validation, reloading, and dependency injection. The definitive guide to IOptions, IOptionsSnapshot, and IOptionsMonitor.

Using strings and magic values in your code? The Options Pattern brings type-safety and flexibility to your configuration.

📦 Basic Setup

// appsettings.json
{
  "EmailSettings": {
    "SmtpServer": "smtp.gmail.com",
    "SmtpPort": 587,
    "SenderEmail": "noreply@myapp.com",
    "SenderName": "MyApp",
    "EnableSsl": true,
    "MaxRetries": 3
  }
}

// Model
public class EmailSettings
{
    public string SmtpServer { get; set; } = string.Empty;
    public int SmtpPort { get; set; }
    public string SenderEmail { get; set; } = string.Empty;
    public string SenderName { get; set; } = string.Empty;
    public bool EnableSsl { get; set; }
    public int MaxRetries { get; set; }
}

// Registration
builder.Services.Configure<EmailSettings>(
    builder.Configuration.GetSection("EmailSettings"));

🔄 Three Options Types

// 1. IOptions<T> - Singleton (static after startup)
public class EmailService
{
    private readonly EmailSettings _settings;
    public EmailService(IOptions<EmailSettings> options)
    {
        _settings = options.Value; // ✅ Single snapshot
    }
}

// 2. IOptionsSnapshot<T> - Scoped (reloads on change)
public class EmailService
{
    private readonly IOptionsSnapshot<EmailSettings> _options;
    public EmailService(IOptionsSnapshot<EmailSettings> options)
    {
        _options = options; // ✅ Fresh each time
    }
    public void SendEmail()
    {
        var settings = _options.Value; // ✅ Reloaded per request
    }
}

// 3. IOptionsMonitor<T> - Singleton (auto-reloads, change notifications)
public class EmailService
{
    private readonly IOptionsMonitor<EmailSettings> _monitor;
    private readonly IDisposable? _changeListener;
    
    public EmailService(IOptionsMonitor<EmailSettings> monitor)
    {
        _monitor = monitor;
        _changeListener = _monitor.OnChange(settings =>
        {
            Console.WriteLine("Email config changed!");
            // React to changes
        });
    }
}

✅ Validation

// With validation
public class EmailSettings
{
    [Required]
    [MinLength(5)]
    public string SmtpServer { get; set; } = string.Empty;
[Range(1, 65535)]
public int SmtpPort { get; set; }

[EmailAddress]
public string SenderEmail { get; set; } = string.Empty;

[Required]
public string SenderName { get; set; } = string.Empty;

[Range(1, 10)]
public int MaxRetries { get; set; }
}

// Validate on startup
builder.Services.AddOptions<EmailSettings>()
.Bind(builder.Configuration.GetSection("EmailSettings"))
.ValidateDataAnnotations()
.Validate(settings => settings.SmtpPort != 25, "SmtpPort cannot be 25(unsecure)")
.ValidateOnStart();

// 🔥 Throws exception if config is invalid!

💡 Pro Tip: Environment – Specific Config

// appsettings.Development.json
{
"EmailSettings": {
"SmtpServer": "localhost",
"SmtpPort": 1025,
"MaxRetries": 1
}
}

// appsettings.Production.json
{
"EmailSettings": {
"SmtpServer": "smtp.sendgrid.net",
"SmtpPort": 587,
"MaxRetries": 5
}
}

// 💡 Automatic based on ASPNETCORE_ENVIRONMENT

Related posts:

Clean Dependency Injection — Lifetimes That Every Dev Must Master

Clean Dependency Injection — Lifetimes That Every Dev Must Master

.NET Core Apps Restart Too Often in Production

.NET Core Apps Restart Too Often in Production

ASP.NET Core: Fix HTTPS Redirection That Silently Loops Forever Behind a Reverse Proxy Because Forwa...

ASP.NET Core: Fix HTTPS Redirection That Silently Loops Forever Behind a Reverse Proxy Because Forwa...

Views: 13

Post navigation

AsyncLocal and CallContext in C#: Mastering Async Flow State Management
SQL Window Functions: Revolutionizing Reporting Without Subqueries

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (482)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • AÄŸ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • AÄŸ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com