ronnythedev/dotnet-clean-architecture-skills/26-dotnet-options-pattern

Claude Code and agent skill by ronnythedev/dotnet-clean-architecture-skills

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Implements the Options pattern for strongly-typed configuration in .NET. Covers IOptions<T>, IOptionsSnapshot<T>, and IOptionsMonitor<T> with validation and reload support.

Install

npx vskill@latest install ronnythedev/dotnet-clean-architecture-skills/26-dotnet-options-pattern

SKILL.md

Options Pattern for .NET Configuration

Overview

The Options pattern provides strongly-typed access to configuration groups:

  • IOptions<T> - Singleton, read once at startup
  • IOptionsSnapshot<T> - Scoped, reloads per request
  • IOptionsMonitor<T> - Singleton, real-time change notifications

Quick Reference

InterfaceLifetimeSupports ReloadNamed OptionsUse Case
IOptions<T>SingletonNoNoStatic config
IOptionsSnapshot<T>ScopedYesYesRequest-scoped config
IOptionsMonitor<T>SingletonYesYesSingleton services, change notifications

Options Structure

/Application/Options/
├── DatabaseOptions.cs
├── JwtOptions.cs
├── CacheOptions.cs
├── EmailOptions.cs
└── FeatureFlagOptions.cs

Template: Basic Options Class

csharp
// src/{name}.application/Options/DatabaseOptions.cs
namespace {name}.application.options;
/// <summary>
/// Options classes should:
/// - Use the "Options" suffix
/// - Have public getters and setters
/// - Include validation via data annotations or IValidateOptions
/// </summary>
public sealed class DatabaseOptions
{
/// <summary>
/// Configuration section name in appsettings.json
/// </summary>
public const string SectionName = "Database";
/// <summary>
/// Connection string for the primary database
/// </summary>
public required string ConnectionString { get; set; }
/// <summary>
/// Maximum number of connections in the pool
/// </summary>
public int MaxPoolSize { get; set; } = 100;
/// <summary>
/// Minimum number of connections in the pool
/// </summary>
public int MinPoolSize { get; set; } = 5;
/// <summary>
/// Connection timeout in seconds
/// </summary>
public int ConnectionTimeout { get; set; } = 30;
/// <summary>
/// Enable connection pooling
/// </summary>
public bool EnablePooling { get; set; } = true;
/// <summary>
/// Enable query logging for debugging
/// </summary>
public bool EnableQueryLogging { get; set; } = false;
}
Corresponding appsettings.json
json
{
"Database": {
"ConnectionString": "Host=localhost;Database=mydb;Username=postgres;Password=secret",
"MaxPoolSize": 100,
"MinPoolSize": 5,
"ConnectionTimeout": 30,
"EnablePooling": true,
"EnableQueryLogging": false
}
}

Template: Options with Data Annotation Validation

csharp
// src/{name}.application/Options/JwtOptions.cs
using System.ComponentModel.DataAnnotations;
namespace {name}.application.options;
public sealed class JwtOptions
{
public const string SectionName = "Jwt";
[Required(ErrorMessage = "JWT Secret is required")]
[MinLength(32, ErrorMessage = "JWT Secret must be at least 32 characters")]
public required string Secret { get; set; }
[Required(ErrorMessage = "JWT Issuer is required")]
public required string Issuer { get; set; }
[Required(ErrorMessage = "JWT Audience is required")]
public required string Audience { get; set; }
[Range(1, 1440, ErrorMessage = "Access token expiration must be between 1 and 1440 minutes")]
public int AccessTokenExpirationMinutes { get; set; } = 15;
[Range(1, 43200, ErrorMessage = "Refresh token expiration must be between 1 and 43200 minutes")]
public int RefreshTokenExpirationMinutes { get; set; } = 10080; // 7 days
}

Template: Options with Custom Validation

csharp
// src/{name}.application/Options/CacheOptions.cs
namespace {name}.application.options;
public sealed class CacheOptions
{
public const string SectionName = "Cache";
public bool Enabled { get; set; } = true;
public string? RedisConnectionString { get; set; }
public int DefaultExpirationMinutes { get; set; } = 5;
public int SlidingExpirationMinutes { get; set; } = 2;
public string KeyPrefix { get; set; } = string.Empty;
}
// src/{name}.application/Options/Validation/CacheOptionsValidator.cs
using Microsoft.Extensions.Options;
namespace {name}.application.options.validation;
/// <summary>
/// Custom validation using IValidateOptions for complex rules
/// </summary>
public sealed class CacheOptionsValidator : IValidateOptions<CacheOptions>
{
public ValidateOptionsResult Validate(string? name, CacheOptions options)
{
var failures = new List<string>();
if (options.Enabled && string.IsNullOrWhiteSpace(options.RedisConnectionString))
{
failures.Add("RedisConnectionString is required when caching is enabled");
}
if (options.DefaultExpirationMinutes < 1)
{
failures.Add("DefaultExpirationMinutes must be at least 1");
}
if (options.SlidingExpirationMinutes >= options.DefaultExpirationMinutes)
{
failures.Add("SlidingExpirationMinutes must be less than DefaultExpirationMinutes");
}
return failures.Count > 0
? ValidateOptionsResult.Fail(failures)
: ValidateOptionsResult.Success;
}
}

Template: Registration in DependencyInjection

csharp
// src/{name}.application/DependencyInjection.cs
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using {name}.application.options;
using {name}.application.options.validation;
namespace {name}.application;
public static class DependencyInjection
{
public static IServiceCollection AddApplication(
this IServiceCollection services,
IConfiguration configuration)
{
// ═══════════════════════════════════════════════════════════════
// BASIC OPTIONS BINDING
// ═══════════════════════════════════════════════════════════════
services.Configure<DatabaseOptions>(
configuration.GetSection(DatabaseOptions.SectionName));
// ═══════════════════════════════════════════════════════════════
// OPTIONS WITH DATA ANNOTATION VALIDATION
// Validates at startup - fails fast if invalid
// ═══════════════════════════════════════════════════════════════
services.AddOptions<JwtOptions>()
.Bind(configuration.GetSection(JwtOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart(); // Validates immediately at startup
// ═══════════════════════════════════════════════════════════════
// OPTIONS WITH CUSTOM VALIDATION
// ═══════════════════════════════════════════════════════════════
services.AddOptions<CacheOptions>()
.Bind(configuration.GetSection(CacheOptions.SectionName))
.ValidateDataAnnotations()
.ValidateOnStart();
services.AddSingleton<IValidateOptions<CacheOptions>, CacheOptionsValidator>();
// ═══════════════════════════════════════════════════════════════
// OPTIONS WITH POST-CONFIGURE
// Modify options after binding
// ═══════════════════════════════════════════════════════════════
services.PostConfigure<DatabaseOptions>(options =>
{
// Apply environment-specific modifications
if (string.IsNullOrEmpty(options.ConnectionString))
{
options.ConnectionString = Environment.GetEnvironmentVariable("DATABASE_URL")
?? throw new InvalidOperationException("Database connection string not configured");
}
});
return services;
}
}

Template: Using IOptions<T> (Singleton Services)

csharp
// src/{name}.infrastructure/Services/JwtTokenService.cs
using Microsoft.Extensions.Options;
using {name}.application.options;
namespace {name}.infrastructure.services;
/// <summary>
/// Use IOptions<T> for:
/// - Singleton services
/// - Configuration that doesn't change at runtime
/// - Best performance (read once, cached forever)
/// </summary>
public sealed class JwtTokenService : IJwtTokenService
{
private readonly JwtOptions _options;
public JwtTokenService(IOptions<JwtOptions> options)
{
// .Value reads the options once
_options = options.Value;
}
public string GenerateAccessToken(User user)
{
var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_options.Secret));
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Id.ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email.Value),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};
var token = new JwtSecurityToken(
issuer: _options.Issuer,
audience: _options.Audience,
claims: claims,
expires: DateTime.UtcNow.AddMinutes(_options.AccessTokenExpirationMinutes),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256));
return new JwtSecurityTokenHandler().WriteToken(token);
}
}

Template: Using IOptionsSnapshot<T> (Scoped Services)

csharp
// src/{name}.application/Features/Email/SendEmail/SendEmailHandler.cs
using Microsoft.Extensions.Options;
using {name}.application.options;
namespace {name}.application.features.email;
/// <summary>
/// Use IOptionsSnapshot<T> for:
/// - Scoped services (per-request in web apps)
/// - Configuration that may change between requests
/// - Named options support
///
/// NOTE: Cannot inject into singleton services!
/// </summary>
public sealed class SendEmailHandler : ICommandHandler<SendEmailCommand, Result>
{
private readonly EmailOptions _options;
private readonly IEmailSender _emailSender;
public SendEmailHandler(
IOptionsSnapshot<EmailOptions> options,
IEmailSender emailSender)
{
// Gets fresh value for each request
_options = options.Value;
_emailSender = emailSender;
}
public async Task<Result> Handle(
SendEmailCommand command,
CancellationToken cancellationToken)
{
if (!_options.Enabled)
{
return Result.Success(); // Email disabled
}
await _emailSender.SendAsync(
to: command.To,
subject: command.Subject,
body: command.Body,
from: _options.FromAddress);
return Result.Success();
}
}

Template: Using IOptionsMonitor<T> (Singleton with Change Notifications)

csharp
// src/{name}.infrastructure/Services/FeatureFlagService.cs
using Microsoft.Extensions.Options;
using {name}.application.options;
namespace {name}.infrastructure.services;
/// <summary>
/// Use IOptionsMonitor<T> for:
/// - Singleton services that need updated configuration
/// - Real-time configuration changes without restart
/// - Background services and hosted services
/// </summary>
public sealed class FeatureFlagService : IFeatureFlagService, IDisposable
{
private readonly IOptionsMonitor<FeatureFlagOptions> _optionsMonitor;
private readonly ILogger<FeatureFlagService> _logger;
private readonly IDisposable? _changeListener;
public FeatureFlagService(
IOptionsMonitor<FeatureFlagOptions> optionsMonitor,
ILogger<FeatureFlagService> logger)
{
_optionsMonitor = optionsMonitor;
_logger = logger;
// ═══════════════════════════════════════════════════════════════
// CHANGE NOTIFICATION
// Subscribe to configuration changes
// ═══════════════════════════════════════════════════════════════
_changeListener = _optionsMonitor.OnChange((options, name) =>
{
_logger.LogInformation(
"Feature flags updated. DarkMode: {DarkMode}, BetaFeatures: {BetaFeatures}",
options.EnableDarkMode,
options.EnableBetaFeatures);
});
}

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
64
Repository forks
11
7-day trend score
21

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/ronnythedev/dotnet-clean-architecture-skills/26-dotnet-options-pattern/badge)](https://verified-skill.com/skills/ronnythedev/dotnet-clean-architecture-skills/26-dotnet-options-pattern)

Something wrong with this skill or its page? Tell us.