Skip to main content

arolariu.Backend.Common.Options

arolariu.Backend.Common

arolariu.Backend.Common.Options Namespace

Classes

ApplicationOptions Class

Provides the foundational configuration structure for the arolariu.ro backend application. This abstract base class defines all configuration properties required across different deployment environments, supporting both cloud-based Azure services and local development infrastructure.

public abstract class ApplicationOptions

Inheritance System.Object 🡒 ApplicationOptions

Derived
AzureOptions
LocalOptions

Remarks

This class serves as the configuration contract for the application, organizing settings into logical groups:

  • Azure infrastructure configuration (tenants, authentication)
  • External service endpoints (storage, databases, AI services)
  • Security and authentication settings (JWT configuration)
  • Application metadata and branding information

The design supports environment-specific implementations through derived classes:

  • AzureOptions for cloud deployments using Azure services
  • LocalOptions for local development with emulated or alternative services

Configuration values are populated from multiple sources in order of precedence:

  1. Environment variables (highest priority)
  2. Azure App Configuration or local configuration files
  3. Azure Key Vault or local secrets storage
  4. Default values defined in this class (lowest priority)

All sensitive information (connection strings, API keys, secrets) should be stored securely and never committed to source control. Use Azure Key Vault for cloud deployments and local secret management tools for development.

Properties

ApplicationOptions.ApplicationAuthor Property

Gets or sets the name of the application author or organization. This information provides attribution and contact context for the application.

public string ApplicationAuthor { get; set; }

Property Value

System.String
A string representing the author's name or organization. Example: "Alexandru-Razvan Olariu" or "AROLARIU.RO"

Remarks

Author information is used for: - Copyright notices and legal attribution - Contact information in API documentation - Support and maintenance identification - Intellectual property tracking

ApplicationOptions.ApplicationDescription Property

Gets or sets a brief description of the application's purpose and capabilities. This description appears in API documentation and helps users understand the application's function.

public string ApplicationDescription { get; set; }

Property Value

System.String
A string containing a concise description of the application. Should explain the primary business purpose and key features.

Remarks

The description is displayed in: - OpenAPI/Swagger documentation - Developer portals and API catalogs - Monitoring and management dashboards - System documentation and guides

ApplicationOptions.ApplicationInsightsEndpoint Property

Gets or sets the endpoint for Application Insights telemetry collection. This endpoint receives application metrics, logs, and distributed tracing data for monitoring and diagnostics.

public string ApplicationInsightsEndpoint { get; set; }

Property Value

System.String
A string representing the Application Insights connection string or instrumentation key. For cloud deployments: Azure Application Insights connection string For local development: Local telemetry endpoint or disabled telemetry collection

Remarks

Telemetry data collected includes:

  • Application performance metrics and response times
  • Error rates and exception details
  • Distributed traces across service boundaries
  • Custom business metrics and events
  • User behavior and usage analytics

Monitoring benefits:

  • Proactive identification of performance issues
  • Root cause analysis for production problems
  • Capacity planning and resource optimization
  • User experience insights and improvements
  • Compliance with SLA requirements

ApplicationOptions.ApplicationName Property

Gets or sets the display name of the application. This name appears in user interfaces, documentation, and system logs.

public string ApplicationName { get; set; }

Property Value

System.String
A string representing the application's display name. Default: "AROLARIU.RO Backend API" or similar branding-appropriate name.

Remarks

Used in various contexts: - API documentation and Swagger UI titles - Error messages and user notifications - Logging and monitoring dashboards - Email templates and communications

ApplicationOptions.ApplicationVersion Property

Gets or sets the current version of the application. This version is used for deployment tracking, debugging, and compatibility management.

public string ApplicationVersion { get; set; }

Property Value

System.String
A string representing the application version (e.g., "1.0.0", "2.1.3-beta"). Should follow semantic versioning (SemVer) conventions when possible.

Remarks

Version information enables: - Deployment and rollback tracking - API compatibility management - Client-server version validation - Support and debugging assistance - Change impact analysis

ApplicationOptions.CognitiveServicesEndpoint Property

Gets or sets the endpoint URI for Azure Cognitive Services. This endpoint provides access to AI services for computer vision, text analysis, and machine learning capabilities.

public string CognitiveServicesEndpoint { get; set; }

Property Value

System.String
A URI string for the Cognitive Services endpoint. For cloud deployments: Azure Cognitive Services endpoint (e.g., "https://myregion\.api\.cognitive\.microsoft\.com/"\) For local development: Alternative ML service endpoint or mock service for testing

Remarks

Cognitive Services capabilities include:

  • Optical Character Recognition (OCR) for document processing
  • Computer vision for image analysis and classification
  • Text analytics for sentiment and entity extraction
  • Language translation and localization services
  • Form recognition for structured document processing

Integration considerations:

  • Handle service quotas and rate limiting
  • Implement fallback strategies for service unavailability
  • Optimize requests to minimize costs and latency
  • Ensure data privacy compliance for processed content

ApplicationOptions.CognitiveServicesKey Property

Gets or sets the API key for authenticating with Cognitive Services. This key enables secure access to AI capabilities and ensures proper usage tracking and billing.

public string CognitiveServicesKey { get; set; }

Property Value

System.String
A string representing the Cognitive Services subscription key. This value should be stored securely and retrieved from the secrets endpoint.

Remarks

Key management best practices: - Store securely in Azure Key Vault or equivalent secrets storage - Use separate keys for different environments (dev, staging, production) - Monitor key usage and regenerate periodically - Implement key rotation without service interruption - Track usage against quotas and billing limits

ApplicationOptions.ConfigurationEndpoint Property

Gets or sets the endpoint URI for the centralized configuration service. This endpoint provides dynamic configuration management and feature flag capabilities.

public string ConfigurationEndpoint { get; set; }

Property Value

System.String
A URI string pointing to the configuration service. For cloud deployments: Azure App Configuration endpoint (e.g., "https://myconfig\.azconfig\.io"\) For local development: Local configuration service or file-based configuration.

Remarks

The configuration endpoint enables:

  • Dynamic configuration updates without application restart
  • Environment-specific configuration management
  • Feature flag implementation and A/B testing
  • Configuration validation and rollback capabilities

Configuration management benefits:

  • Centralized configuration across multiple application instances
  • Real-time configuration updates for operational flexibility
  • Configuration versioning and change tracking
  • Role-based access control for configuration changes

ApplicationOptions.JwtAudience Property

Gets or sets the JWT token audience identifier. This value specifies the intended recipients of the JWT tokens issued for this application.

public string JwtAudience { get; set; }

Property Value

System.String
A string representing the JWT audience (aud claim). Typically the application's identifier or API endpoint that should accept the token.

Remarks

The JWT audience ensures:

  • Tokens are only accepted by intended recipients
  • Protection against token misuse across different applications
  • Clear identification of token scope and purpose
  • Compliance with OAuth 2.0 and OpenID Connect standards

Applications should validate the audience claim to ensure tokens are intended for their specific service or API endpoints.

ApplicationOptions.JwtIssuer Property

Gets or sets the JWT token issuer identifier. This value identifies the authentication authority that issues tokens for the application.

public string JwtIssuer { get; set; }

Property Value

System.String
A string representing the JWT issuer (iss claim). Typically the application's domain or a unique identifier for the authentication service.

Remarks

The JWT issuer is used for:

  • Token validation and trust establishment
  • Multi-tenant authentication scenarios
  • Integration with external identity providers
  • Security auditing and token lifecycle management

The issuer must be consistent across all application instances and should be verified during token validation to prevent token replay attacks.

ApplicationOptions.JwtSecret Property

Gets or sets the secret key used for JWT token signing and validation. This cryptographic key ensures token integrity and authenticity.

public string JwtSecret { get; set; }

Property Value

System.String
A string representing the JWT signing secret. This value must be stored securely and retrieved from the secrets endpoint. Should be a cryptographically strong random string of sufficient length.

Remarks

Critical security requirements:

  • Must be stored in Azure Key Vault or equivalent secure storage
  • Should be at least 256 bits (32 characters) for HS256 algorithm
  • Must be identical across all application instances for token validation
  • Should be rotated regularly with coordinated deployment
  • Never commit to source control or expose in logs

Key rotation strategy:

  • Support multiple keys during rotation periods
  • Implement graceful key rollover without service interruption
  • Monitor token validation failures during rotation
  • Maintain key version history for audit purposes

ApplicationOptions.NoSqlConnectionString Property

Gets or sets the connection string for the NoSQL document database. This database provides scalable storage for flexible schema documents and high-throughput scenarios.

public string NoSqlConnectionString { get; set; }

Property Value

System.String
A connection string for the NoSQL database. For cloud deployments: Azure Cosmos DB connection string with account key or managed identity For local development: Cosmos DB Emulator connection string or alternative NoSQL database

Remarks

The NoSQL database is optimized for:

  • Document storage with flexible schemas
  • High-throughput read and write operations
  • Global distribution and multi-region replication
  • Real-time analytics and reporting scenarios

Design considerations:

  • Partition strategy for optimal performance and cost
  • Consistency levels appropriate for business requirements
  • Indexing policies for query optimization
  • Request unit (RU) provisioning and auto-scaling
  • Data modeling for NoSQL efficiency

ApplicationOptions.SecretsEndpoint Property

Gets or sets the endpoint URI for the secrets storage service. This endpoint provides secure access to application secrets and sensitive configuration data.

public string SecretsEndpoint { get; set; }

Property Value

System.String
A URI string pointing to the secrets storage service. For cloud deployments: Azure Key Vault URI (e.g., "https://myvault\.vault\.azure\.net/"\) For local development: Local secrets store endpoint or file path.

Remarks

The secrets endpoint is used to retrieve:

  • Database connection strings with embedded credentials
  • API keys for third-party services
  • JWT signing secrets and encryption keys
  • OAuth client secrets and certificates

Security considerations:

  • Access should be restricted using managed identities or service principals
  • Secrets should be rotated regularly according to security policies
  • Access patterns should be monitored and audited
  • Secrets should never be logged or exposed in error messages

ApplicationOptions.SqlConnectionString Property

Gets or sets the connection string for the relational SQL database. This database stores structured business data requiring ACID compliance and complex queries.

public string SqlConnectionString { get; set; }

Property Value

System.String
A connection string for the SQL database. For cloud deployments: Azure SQL Database connection string with managed identity or SQL authentication For local development: SQL Server Express or LocalDB connection string

Remarks

The SQL database typically contains:

  • User account and profile information
  • Transactional business data requiring consistency
  • Configuration data with complex relationships
  • Audit logs and compliance tracking information

Security and performance considerations:

  • Use managed identities or Azure AD authentication when possible
  • Implement connection pooling and retry logic
  • Configure appropriate backup and disaster recovery
  • Monitor query performance and optimize indexes
  • Encrypt sensitive data at rest and in transit

ApplicationOptions.StorageAccountEndpoint Property

Gets or sets the complete endpoint URI for the storage account. This endpoint provides programmatic access to blob, queue, and table storage services.

public string StorageAccountEndpoint { get; set; }

Property Value

System.String
A URI string for the storage account endpoint. For cloud deployments: Azure Storage endpoint (e.g., "https://mystorageaccount\.blob\.core\.windows\.net/"\) For local development: Azurite emulator endpoint (e.g., "http://127\.0\.0\.1:10000/devstoreaccount1"\)

Remarks

Storage services accessed through this endpoint:

  • Blob storage for unstructured data and files
  • Queue storage for reliable message processing
  • Table storage for NoSQL data scenarios
  • File storage for shared file system access

Performance and reliability considerations:

  • Configure appropriate redundancy levels (LRS, GRS, RA-GRS)
  • Implement retry policies for transient failures
  • Use CDN integration for global content distribution
  • Monitor storage metrics and implement lifecycle policies

ApplicationOptions.StorageAccountName Property

Gets or sets the name of the primary storage account for blob and file storage. This account hosts static assets, user uploads, and application data files.

public string StorageAccountName { get; set; }

Property Value

System.String
A string representing the storage account name. For cloud deployments: Azure Storage account name (e.g., "mystorageaccount") For local development: Azurite emulator account name or alternative storage identifier.

Remarks

The storage account is used for: - Static web assets (images, documents, media files) - User-generated content and file uploads - Application logs and diagnostic data - Backup and archival storage for business data

ApplicationOptions.TenantId Property

Gets or sets the Azure Active Directory tenant identifier. This GUID identifies the Azure AD tenant for authentication and authorization operations.

public string TenantId { get; set; }

Property Value

System.String
A GUID string representing the Azure AD tenant ID. Required for Azure-based authentication. For local development, this may be empty if using alternative authentication mechanisms.

Remarks

The tenant ID is used for: - Azure AD authentication and token validation - Multi-tenant application scenarios - Azure service-to-service authentication - Managed Identity configuration in Azure deployments

ApplicationOptions.TermsAndConditions Property

Gets or sets the terms and conditions text or URL for the application. This content defines the legal terms governing the use of the application and its services.

public string TermsAndConditions { get; set; }

Property Value

System.String
A string containing terms and conditions text or a URL to the full terms document. Should be accessible to all users and comply with applicable legal requirements.

Remarks

Terms and conditions typically cover:

  • Acceptable use policies and restrictions
  • Data privacy and protection commitments
  • Service availability and performance expectations
  • Limitation of liability and legal disclaimers
  • User rights and responsibilities

Legal considerations:

  • Must comply with applicable jurisdictional requirements
  • Should be reviewed by legal counsel
  • Must be accessible and clearly presented to users
  • Should be versioned and change tracking implemented

AzureOptions Class

Provides configuration options specifically for Azure cloud-based deployments. This class inherits all base configuration properties and may include Azure-specific extensions in the future.

public sealed class AzureOptions : arolariu.Backend.Common.Options.ApplicationOptions

Inheritance System.Object 🡒 ApplicationOptions 🡒 AzureOptions

Remarks

AzureOptions is designed for production deployments leveraging Microsoft Azure services:

  • Azure Active Directory for authentication and authorization
  • Azure Key Vault for secrets management
  • Azure App Configuration for centralized configuration
  • Azure Storage for blob and file storage
  • Azure SQL Database and Cosmos DB for data persistence
  • Azure Cognitive Services and OpenAI for AI capabilities

This class currently inherits all functionality from ApplicationOptions but provides a distinct type for dependency injection and configuration binding. Future Azure-specific features and optimizations will be added to this class.

CloudOptionsManager Class

Provides configuration management for cloud-based Azure deployments. This implementation retrieves configuration from Azure services including Key Vault and App Configuration, supporting dynamic configuration updates and secure secrets management.

public class CloudOptionsManager : arolariu.Backend.Common.Options.IOptionsManager

Inheritance System.Object 🡒 CloudOptionsManager

Implements IOptionsManager

Example

// Registration in dependency injection container
services.Configure<AzureOptions>(configuration.GetSection("AzureOptions"));
services.AddSingleton<IOptionsManager, CloudOptionsManager>();

// Usage in application services
public class DocumentService
{
private readonly ApplicationOptions _options;

public DocumentService(IOptionsManager optionsManager)
{
_options = optionsManager.GetApplicationOptions();
}

public async Task ProcessDocumentAsync()
{
// Configuration is automatically kept up-to-date
var cognitiveEndpoint = _options.CognitiveServicesEndpoint;
var storageConnection = _options.StorageAccountEndpoint;

// Use current configuration values
var cognitiveClient = new AzureAIClient(new Uri(cognitiveEndpoint), new DefaultAzureCredential());
}
}

Remarks

The CloudOptionsManager is specifically designed for production deployments in Microsoft Azure, leveraging Azure's configuration and secrets management services to provide:

Azure Service Integration: - Azure Key Vault for secure storage of secrets and sensitive configuration - Azure App Configuration for centralized, dynamic configuration management - Managed Identity authentication for secure, credential-free access - Environment-specific configuration through labels and feature flags

Dynamic Configuration Support: This implementation uses Microsoft.Extensions.Options.IOptionsMonitor<> to enable: - Real-time configuration updates without application restart - Automatic refresh when configuration changes in Azure services - Change notifications for configuration-dependent services - Fallback mechanisms when external services are temporarily unavailable

Security and Compliance: - Secure retrieval of sensitive configuration from Azure Key Vault - Role-based access control (RBAC) for configuration access - Audit logging of configuration access and changes - Encryption in transit and at rest for all configuration data

Operational Benefits: - Centralized configuration management across multiple application instances - Configuration versioning and rollback capabilities - Integration with Azure monitoring and alerting services - Support for blue-green deployments and configuration testing

Constructors

CloudOptionsManager(IOptionsMonitor<AzureOptions>) Constructor

Provides configuration management for cloud-based Azure deployments. This implementation retrieves configuration from Azure services including Key Vault and App Configuration, supporting dynamic configuration updates and secure secrets management.

public CloudOptionsManager(Microsoft.Extensions.Options.IOptionsMonitor<arolariu.Backend.Common.Options.AzureOptions> azureOptionsMonitor);

Parameters

azureOptionsMonitor Microsoft.Extensions.Options.IOptionsMonitor<AzureOptions>

Example

// Registration in dependency injection container
services.Configure<AzureOptions>(configuration.GetSection("AzureOptions"));
services.AddSingleton<IOptionsManager, CloudOptionsManager>();

// Usage in application services
public class DocumentService
{
private readonly ApplicationOptions _options;

public DocumentService(IOptionsManager optionsManager)
{
_options = optionsManager.GetApplicationOptions();
}

public async Task ProcessDocumentAsync()
{
// Configuration is automatically kept up-to-date
var cognitiveEndpoint = _options.CognitiveServicesEndpoint;
var storageConnection = _options.StorageAccountEndpoint;

// Use current configuration values
var cognitiveClient = new AzureAIClient(new Uri(cognitiveEndpoint), new DefaultAzureCredential());
}
}

Remarks

The CloudOptionsManager is specifically designed for production deployments in Microsoft Azure, leveraging Azure's configuration and secrets management services to provide:

Azure Service Integration: - Azure Key Vault for secure storage of secrets and sensitive configuration - Azure App Configuration for centralized, dynamic configuration management - Managed Identity authentication for secure, credential-free access - Environment-specific configuration through labels and feature flags

Dynamic Configuration Support: This implementation uses Microsoft.Extensions.Options.IOptionsMonitor<> to enable: - Real-time configuration updates without application restart - Automatic refresh when configuration changes in Azure services - Change notifications for configuration-dependent services - Fallback mechanisms when external services are temporarily unavailable

Security and Compliance: - Secure retrieval of sensitive configuration from Azure Key Vault - Role-based access control (RBAC) for configuration access - Audit logging of configuration access and changes - Encryption in transit and at rest for all configuration data

Operational Benefits: - Centralized configuration management across multiple application instances - Configuration versioning and rollback capabilities - Integration with Azure monitoring and alerting services - Support for blue-green deployments and configuration testing

Fields

CloudOptionsManager.AzureOptionsMonitor Field

Monitors Azure configuration options and provides automatic updates when configuration changes. This monitor integrates with Azure App Configuration and Key Vault to deliver real-time configuration management.

private readonly IOptionsMonitor<AzureOptions> AzureOptionsMonitor;

Field Value

Microsoft.Extensions.Options.IOptionsMonitor<AzureOptions>

Exceptions

System.ArgumentNullException
Thrown when the azureOptionsMonitor parameter is null during construction.

Remarks

The options monitor provides several key capabilities for cloud deployments:

Automatic Refresh: - Polls Azure App Configuration for changes at configured intervals - Receives push notifications when configuration changes (if configured) - Updates Key Vault secrets when refresh intervals expire - Maintains cache consistency across multiple application instances

Change Detection: - Tracks configuration version and etag values - Detects changes in both App Configuration and Key Vault - Provides change notifications to dependent services - Supports selective refresh of specific configuration sections

Error Handling: - Maintains last known good configuration during service outages - Implements exponential backoff for failed refresh attempts - Logs configuration retrieval errors and warnings - Provides fallback values when external services are unavailable

Performance Optimization: - Caches configuration values to minimize Azure service calls - Uses conditional requests to reduce bandwidth and costs - Implements efficient polling strategies based on configuration volatility - Supports burst protection during high-frequency change scenarios

Methods

CloudOptionsManager.GetApplicationOptions() Method

Retrieves the complete application configuration options. This method provides access to all configuration settings required by the application, including service endpoints, authentication settings, and operational parameters.

public arolariu.Backend.Common.Options.ApplicationOptions GetApplicationOptions();

Implements GetApplicationOptions()

Returns

ApplicationOptions
An ApplicationOptions instance containing all application configuration values. The returned object includes settings for databases, external services, authentication, and application metadata.

Exceptions

System.InvalidOperationException
Thrown when required configuration values are missing or invalid.

System.UnauthorizedAccessException
Thrown when the application lacks permissions to access configuration sources.

System.Net.Http.HttpRequestException
Thrown when external configuration services are unavailable or return errors.

Example

// Basic usage
var options = optionsManager.GetApplicationOptions();

// Access specific configuration sections
var databaseConnection = options.SqlConnectionString;
var jwtSettings = new
{
Issuer = options.JwtIssuer,
Audience = options.JwtAudience,
Secret = options.JwtSecret
};

// Use configuration for service initialization
var storageClient = new BlobServiceClient(options.StorageAccountEndpoint);

Remarks

This method should return a fully populated configuration object with values retrieved from the appropriate sources for the current environment. The implementation is responsible for:

Configuration Retrieval: - Merging values from multiple configuration sources - Applying environment-specific overrides - Resolving configuration references and dependencies - Handling missing or invalid configuration gracefully

Security Considerations: - Retrieving sensitive values from secure storage (Azure Key Vault) - Avoiding exposure of secrets in logs or error messages - Implementing proper authentication for configuration access - Validating configuration integrity and authenticity

Performance Considerations: - Caching configuration values to minimize external calls - Implementing refresh mechanisms for dynamic configuration - Handling configuration service outages gracefully - Minimizing startup time through efficient configuration loading

Error Handling: The method should handle configuration errors appropriately: - Provide meaningful error messages for missing required configuration - Implement fallback mechanisms for non-critical settings - Log configuration issues for troubleshooting - Fail fast for invalid or incompatible configuration

LocalOptions Class

Provides configuration options for local development and testing environments. This class supports development scenarios using local services, emulators, and alternative providers.

public sealed class LocalOptions : arolariu.Backend.Common.Options.ApplicationOptions

Inheritance System.Object 🡒 ApplicationOptions 🡒 LocalOptions

Remarks

LocalOptions enables development without requiring full Azure infrastructure:

  • Local authentication providers or development tokens
  • File-based or simple database storage for secrets and configuration
  • Azurite emulator for blob storage testing
  • SQL Server Express or LocalDB for relational data
  • Cosmos DB Emulator for document database development
  • Local AI service proxies or mock implementations

This configuration approach facilitates:

  • Offline development and testing
  • Reduced cloud service costs during development
  • Faster development iteration cycles
  • Simplified debugging and troubleshooting
  • Team development with minimal infrastructure dependencies

LocalOptionsManager Class

Provides configuration management for local development and testing environments. This implementation uses file-based configuration sources and local services, enabling development without requiring cloud infrastructure dependencies.

public class LocalOptionsManager : arolariu.Backend.Common.Options.IOptionsManager

Inheritance System.Object 🡒 LocalOptionsManager

Implements IOptionsManager

Example

// Registration in dependency injection container for development
services.Configure<LocalOptions>(configuration.GetSection("LocalOptions"));
services.AddSingleton<IOptionsManager, LocalOptionsManager>();

// Example appsettings.Development.json configuration
{
"LocalOptions": {
"SqlConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ArolariumDev;Trusted_Connection=true;",
"NoSqlConnectionString": "AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
"StorageAccountEndpoint": "http://127.0.0.1:10000/devstoreaccount1",
"CognitiveServicesEndpoint": "https://cognitiveservices.localhost/",
"ApplicationName": "AROLARIU.RO Backend API (Development)"
}
}

// Usage remains the same as cloud implementation
public class LocalDevelopmentService
{
private readonly ApplicationOptions _options;

public LocalDevelopmentService(IOptionsManager optionsManager)
{
_options = optionsManager.GetApplicationOptions();
}
}

Remarks

The LocalOptionsManager is designed to support development workflows and testing scenarios where full cloud infrastructure is not available or desired. It provides:

Local Development Support: - File-based configuration using appsettings.json and environment-specific files - Environment variable overrides for developer-specific settings - Local secrets storage using user secrets or environment variables - Support for development tools and emulators (Azurite, Cosmos DB Emulator)

Configuration Sources: The local implementation typically uses: - appsettings.json for base configuration - appsettings.Development.json for development-specific overrides - User secrets for sensitive development data - Environment variables for machine-specific settings - Command-line arguments for runtime overrides

Testing and CI/CD Benefits: - Isolated configuration for unit and integration tests - No external service dependencies for build pipelines - Predictable configuration for automated testing - Fast startup times without network configuration calls - Simplified debugging and troubleshooting

Development Team Advantages: - Reduced cloud service costs during development - Offline development capability - Consistent development environment setup - Easy configuration sharing through source control - Quick iteration cycles without cloud dependencies

Constructors

LocalOptionsManager(IOptionsMonitor<LocalOptions>) Constructor

Provides configuration management for local development and testing environments. This implementation uses file-based configuration sources and local services, enabling development without requiring cloud infrastructure dependencies.

public LocalOptionsManager(Microsoft.Extensions.Options.IOptionsMonitor<arolariu.Backend.Common.Options.LocalOptions> localOptionsMonitor);

Parameters

localOptionsMonitor Microsoft.Extensions.Options.IOptionsMonitor<LocalOptions>

An Microsoft.Extensions.Options.IOptionsMonitor<> instance for monitoring local configuration changes. This parameter cannot be null and provides access to LocalOptions configuration.

Example

// Registration in dependency injection container for development
services.Configure<LocalOptions>(configuration.GetSection("LocalOptions"));
services.AddSingleton<IOptionsManager, LocalOptionsManager>();

// Example appsettings.Development.json configuration
{
"LocalOptions": {
"SqlConnectionString": "Server=(localdb)\\mssqllocaldb;Database=ArolariumDev;Trusted_Connection=true;",
"NoSqlConnectionString": "AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==",
"StorageAccountEndpoint": "http://127.0.0.1:10000/devstoreaccount1",
"CognitiveServicesEndpoint": "https://cognitiveservices.localhost/",
"ApplicationName": "AROLARIU.RO Backend API (Development)"
}
}

// Usage remains the same as cloud implementation
public class LocalDevelopmentService
{
private readonly ApplicationOptions _options;

public LocalDevelopmentService(IOptionsManager optionsManager)
{
_options = optionsManager.GetApplicationOptions();
}
}

Remarks

The LocalOptionsManager is designed to support development workflows and testing scenarios where full cloud infrastructure is not available or desired. It provides:

Local Development Support: - File-based configuration using appsettings.json and environment-specific files - Environment variable overrides for developer-specific settings - Local secrets storage using user secrets or environment variables - Support for development tools and emulators (Azurite, Cosmos DB Emulator)

Configuration Sources: The local implementation typically uses: - appsettings.json for base configuration - appsettings.Development.json for development-specific overrides - User secrets for sensitive development data - Environment variables for machine-specific settings - Command-line arguments for runtime overrides

Testing and CI/CD Benefits: - Isolated configuration for unit and integration tests - No external service dependencies for build pipelines - Predictable configuration for automated testing - Fast startup times without network configuration calls - Simplified debugging and troubleshooting

Development Team Advantages: - Reduced cloud service costs during development - Offline development capability - Consistent development environment setup - Easy configuration sharing through source control - Quick iteration cycles without cloud dependencies

Fields

LocalOptionsManager.LocalOptionsMonitor Field

Monitors local configuration options and provides file-based configuration management. This monitor tracks changes to local configuration files and environment variables.

private readonly IOptionsMonitor<LocalOptions> LocalOptionsMonitor;

Field Value

Microsoft.Extensions.Options.IOptionsMonitor<LocalOptions>

Exceptions

System.ArgumentNullException
Thrown when the localOptionsMonitor parameter is null during construction.

Remarks

The local options monitor provides development-focused capabilities:

File-based Configuration Management: - Monitors appsettings.json and environment-specific files for changes - Automatically reloads configuration when files are modified during development - Supports hot-reload scenarios for rapid development iteration - Maintains configuration hierarchy: command-line > environment variables > files

Development Workflow Integration: - Works with Visual Studio and VS Code configuration reload features - Supports user secrets for sensitive development data - Integrates with .NET configuration providers for consistent behavior - Enables configuration debugging through standard .NET logging

Local Service Support: - Configured for local emulators (Azurite, Cosmos DB Emulator, SQL LocalDB) - Default connections to localhost services and development databases - Mock or development endpoints for external services - Simplified authentication using development keys or tokens

Performance Characteristics: - Fast configuration access (file-based, no network calls) - Immediate reload when configuration files change - Minimal memory footprint for development scenarios - No external service dependencies or network latency

Methods

LocalOptionsManager.GetApplicationOptions() Method

Retrieves the complete application configuration options. This method provides access to all configuration settings required by the application, including service endpoints, authentication settings, and operational parameters.

public arolariu.Backend.Common.Options.ApplicationOptions GetApplicationOptions();

Implements GetApplicationOptions()

Returns

ApplicationOptions
An ApplicationOptions instance containing all application configuration values. The returned object includes settings for databases, external services, authentication, and application metadata.

Exceptions

System.InvalidOperationException
Thrown when required configuration values are missing or invalid.

System.UnauthorizedAccessException
Thrown when the application lacks permissions to access configuration sources.

System.Net.Http.HttpRequestException
Thrown when external configuration services are unavailable or return errors.

Example

// Basic usage
var options = optionsManager.GetApplicationOptions();

// Access specific configuration sections
var databaseConnection = options.SqlConnectionString;
var jwtSettings = new
{
Issuer = options.JwtIssuer,
Audience = options.JwtAudience,
Secret = options.JwtSecret
};

// Use configuration for service initialization
var storageClient = new BlobServiceClient(options.StorageAccountEndpoint);

Remarks

This method should return a fully populated configuration object with values retrieved from the appropriate sources for the current environment. The implementation is responsible for:

Configuration Retrieval: - Merging values from multiple configuration sources - Applying environment-specific overrides - Resolving configuration references and dependencies - Handling missing or invalid configuration gracefully

Security Considerations: - Retrieving sensitive values from secure storage (Azure Key Vault) - Avoiding exposure of secrets in logs or error messages - Implementing proper authentication for configuration access - Validating configuration integrity and authenticity

Performance Considerations: - Caching configuration values to minimize external calls - Implementing refresh mechanisms for dynamic configuration - Handling configuration service outages gracefully - Minimizing startup time through efficient configuration loading

Error Handling: The method should handle configuration errors appropriately: - Provide meaningful error messages for missing required configuration - Implement fallback mechanisms for non-critical settings - Log configuration issues for troubleshooting - Fail fast for invalid or incompatible configuration

Interfaces

IOptionsManager Interface

Defines the contract for retrieving and managing application configuration options. This interface abstracts the configuration retrieval mechanism, enabling different implementations for various deployment environments and configuration sources.

public interface IOptionsManager

Derived
CloudOptionsManager
LocalOptionsManager

Example

// Dependency injection registration
services.AddSingleton<IOptionsManager, CloudOptionsManager>();

// Usage in a service
public class InvoiceService
{
private readonly ApplicationOptions _options;

public InvoiceService(IOptionsManager optionsManager)
{
_options = optionsManager.GetApplicationOptions();
}

public async Task ProcessInvoiceAsync()
{
var connectionString = _options.NoSqlConnectionString;
// Use configuration for business logic
}
}

Remarks

The IOptionsManager interface provides a unified abstraction for accessing application configuration regardless of the underlying storage mechanism or environment. This design enables:

Environment Flexibility: - Cloud deployments using Azure Key Vault and App Configuration - Local development using file-based configuration or environment variables - Testing scenarios with mock or in-memory configuration providers - Container deployments with orchestrator-managed configuration

Configuration Sources: The interface abstracts various configuration sources including: - Azure Key Vault for secure secrets storage - Azure App Configuration for centralized settings management - Local JSON files for development and testing - Environment variables for container and deployment scenarios - Database storage for dynamic configuration scenarios

Implementation Strategy: Implementations should follow the configuration precedence hierarchy: 1. Environment variables (highest precedence) 2. Command-line arguments 3. External configuration services (Azure App Configuration) 4. Local configuration files 5. Default values (lowest precedence)

The interface is designed for dependency injection, allowing consumers to depend on the abstraction rather than concrete configuration implementations. This promotes testability and environment-specific configuration without code changes.

Methods

IOptionsManager.GetApplicationOptions() Method

Retrieves the complete application configuration options. This method provides access to all configuration settings required by the application, including service endpoints, authentication settings, and operational parameters.

arolariu.Backend.Common.Options.ApplicationOptions GetApplicationOptions();

Returns

ApplicationOptions
An ApplicationOptions instance containing all application configuration values. The returned object includes settings for databases, external services, authentication, and application metadata.

Exceptions

System.InvalidOperationException
Thrown when required configuration values are missing or invalid.

System.UnauthorizedAccessException
Thrown when the application lacks permissions to access configuration sources.

System.Net.Http.HttpRequestException
Thrown when external configuration services are unavailable or return errors.

Example

// Basic usage
var options = optionsManager.GetApplicationOptions();

// Access specific configuration sections
var databaseConnection = options.SqlConnectionString;
var jwtSettings = new
{
Issuer = options.JwtIssuer,
Audience = options.JwtAudience,
Secret = options.JwtSecret
};

// Use configuration for service initialization
var storageClient = new BlobServiceClient(options.StorageAccountEndpoint);

Remarks

This method should return a fully populated configuration object with values retrieved from the appropriate sources for the current environment. The implementation is responsible for:

Configuration Retrieval: - Merging values from multiple configuration sources - Applying environment-specific overrides - Resolving configuration references and dependencies - Handling missing or invalid configuration gracefully

Security Considerations: - Retrieving sensitive values from secure storage (Azure Key Vault) - Avoiding exposure of secrets in logs or error messages - Implementing proper authentication for configuration access - Validating configuration integrity and authenticity

Performance Considerations: - Caching configuration values to minimize external calls - Implementing refresh mechanisms for dynamic configuration - Handling configuration service outages gracefully - Minimizing startup time through efficient configuration loading

Error Handling: The method should handle configuration errors appropriately: - Provide meaningful error messages for missing required configuration - Implement fallback mechanisms for non-critical settings - Log configuration issues for troubleshooting - Fail fast for invalid or incompatible configuration

// was this page useful?