Common Configurations
Overview
Welcome to the comprehensive configuration guide for YourProject! This document is your roadmap to understanding and implementing the powerful configuration system that makes FlexBase applications both robust and easy to manage.
Why Configuration Matters? π―
Zero Downtime Deployments: Change settings without code changes
Environment Consistency: Same code, different behaviors per environment
Security by Design: Sensitive data protection across all environments
Developer Productivity: One configuration system for all endpoints
Operational Excellence: Centralized logging, monitoring, and troubleshooting
What You'll Learn π
How to set up configurations that scale from development to production
Best practices that save you hours of debugging and maintenance
Security patterns that protect your application and data
Performance optimizations that make your app lightning-fast
Troubleshooting techniques that solve 90% of common issues
Configuration Architecture
The Power of Layered Configuration ποΈ
FlexBase uses a sophisticated 3-tier configuration system that gives you the perfect balance of consistency and flexibility:
1. Common Configurations - Your Foundation Layer
Value: Eliminates configuration duplication and ensures consistency
What it does: Shared settings across ALL endpoints
Why it matters: Change once, apply everywhere
Real benefit: No more hunting through 10+ files to update a database connection
2. Environment-Specific Configurations - Your Environment Layer
Value: Same code, different behavior per environment
What it does: Overrides common settings for specific environments
Why it matters: Development logs everything, Production logs only errors
Real benefit: Zero code changes needed when promoting from Dev β Staging β Production
3. Endpoint-Specific Configurations - Your Customization Layer
Value: Fine-tuned control for unique endpoint requirements
What it does: Additional settings for individual endpoints
Why it matters: Web API might need CORS, but Message Handlers don't
Real benefit: Each endpoint optimized for its specific role
Configuration Files Structure π
YourProject.Application/
βββ EndPoints/
β βββ YourProject.EndPoint.CommonConfigs/ β π― THE CONTROL CENTER
β β βββ AppSettings/
β β βββ appsettings.Common.Development.json β Dev settings for ALL
β β βββ appsettings.Common.Production.json β Prod settings for ALL
β β βββ appsettings.Common.Staging.json β Staging settings for ALL
β βββ YourProject.EndPoint.WebAPI/ β π INDIVIDUAL ENDPOINTS
β βββ appsettings.json β Base settings
β βββ appsettings.Development.json β Dev overrides
β βββ appsettings.Production.json β Prod overrides
π‘ Pro Tip: The magic happens in the CommonConfigs folder - this is where you make changes that affect your entire application ecosystem!
Common Configuration Sections
1. Serilog Configuration - Your Application's Eyes and Ears ποΈ
Why Serilog is a Game-Changer π
Structured Logging: Search and filter logs like a database
Performance: 10x faster than traditional logging
Flexibility: Log to console, files, databases, or cloud services
Debugging Superpowers: Trace requests across multiple services
Production Ready: Built-in log rotation and retention
What This Configuration Gives You πͺ
Instant Problem Detection: See issues before users do
Request Tracing: Follow a user's journey through your entire system
Performance Monitoring: Identify slow operations automatically
Audit Trail: Complete record of all system activities
Zero-Downtime Logging: Change log levels without restarting
{
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"MinimumLevel": {
"Default": "YourLogLevel",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId" ],
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "YourLogPath\\log.txt",
"rollingInterval": "Day",
"retainedFileCountLimit": 7,
"retainedFileDuration": "7.00:00:00"
}
}
],
"Properties": {
"Application": "YourProjectName"
}
}
}
Configuration Deep Dive π
MinimumLevel - Your Logging Intelligence π§
Verbose: "I want to see EVERYTHING" (Development)
Debug: "Show me detailed flow" (Development/Staging)
Information: "Tell me what's happening" (Production)
Warning: "Something might be wrong" (Production)
Error: "Something IS wrong" (Production)
Fatal: "System is crashing" (Production)
WriteTo - Your Logging Destinations π
Console: Perfect for development and debugging
File: Reliable storage with automatic rotation
Database: Searchable logs with SQL queries
Cloud: Centralized logging across multiple servers
Enrich - Your Context Superpowers β‘
FromLogContext: Adds custom properties to every log
WithMachineName: Know which server logged the message
WithProcessId: Track logs from specific processes
WithThreadId: Debug multi-threading issues
Real-World Example: In an e-commerce system, you might set
"Application": "ECommerce"
and configure different log levels for Development (Verbose) and Production (Information). This means developers see every detail during development, but production only logs what matters for monitoring and troubleshooting.
2. FlexBase Configuration - The Heart of Your Application β€οΈ
Why FlexBase Configuration is Revolutionary π
Multi-Database Support: SQL Server, MySQL, PostgreSQL - choose your weapon
CQRS Built-In: Separate read/write databases for maximum performance
Multi-Tenant Ready: One codebase, multiple customers
Message Bus Flexibility: RabbitMQ, Azure Service Bus, AWS SQS - all supported
Zero Configuration Changes: Switch between transports with one setting
What This Configuration Unlocks π
Massive Performance: Read/write separation = 10x faster queries
Infinite Scalability: Add databases and message brokers as you grow
Enterprise Security: Multi-tenant isolation and secure connections
Cloud Native: Deploy anywhere - on-premises, Azure, AWS, or hybrid
Disaster Recovery: Built-in redundancy and failover capabilities
{
"FlexBase": {
"AppDbConnection": "Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUser;Password=YourPassword;TrustServerCertificate=True",
"AppReadDbConnection": "Data Source=YourServer;Initial Catalog=YourReadDatabase;User ID=YourUser;Password=YourPassword;TrustServerCertificate=True",
"AzureStorageConnectionString": "YourAzureStorageConnectionString",
"SqlTransportConnectionString": "Data Source=YourServer;Initial Catalog=YourTransportDatabase;User ID=YourUser;Password=YourPassword;TrustServerCertificate=True",
"SqlPersistenceConnectionString": "Data Source=YourServer;Initial Catalog=YourPersistenceDatabase;User ID=YourUser;Password=YourPassword;TrustServerCertificate=True",
"RabbitMqConnectionString": "amqp://YourUser:YourPassword@YourRabbitMqHost:YourPort",
"AzureServiceBusConnectionString": "YourAzureServiceBusConnectionString",
"AmazonSQSTransportBucketName": "YourS3BucketName",
"AmazonSQSTransportKeyPrefix": "YourKeyPrefix",
"TenantMasterDbConnection": "Data Source=YourServer;Initial Catalog=YourTenantMasterDatabase;User ID=YourUser;Password=YourPassword;TrustServerCertificate=True"
}
}
Database Connections - Your Data Powerhouse πΎ
AppDbConnection - The Write Master βοΈ
What it does: Handles all CREATE, UPDATE, DELETE operations
Why separate: Write operations are slower and can block reads
Performance gain: 5-10x faster read operations
Real benefit: Your users get instant search results while data is being saved
AppReadDbConnection - The Read Rocket π
What it does: Handles all SELECT queries and reports
Why separate: Read operations are 90% of your traffic
Performance gain: Optimized indexes, no write locks
Real benefit: Sub-second response times even with millions of records
TenantMasterDbConnection - The Multi-Tenant Brain π§
What it does: Manages multiple customer databases
Why separate: Complete data isolation between customers
Security gain: One customer can never see another's data
Real benefit: Enterprise-grade security with simple configuration
Message Bus Connections - Your Communication Network π‘
RabbitMqConnectionString - The Reliable Messenger π°
What it does: Handles all inter-service communication
Why RabbitMQ: Battle-tested, reliable, and fast
Performance gain: 100,000+ messages per second
Real benefit: Your services talk to each other instantly and reliably
AzureServiceBusConnectionString - The Cloud Native βοΈ
What it does: Managed message service in Azure
Why Azure Service Bus: Fully managed, auto-scaling
Performance gain: No infrastructure management needed
Real benefit: Focus on business logic, not message infrastructure
SQL Transport - The Database Native ποΈ
What it does: Uses your existing SQL Server for messaging
Why SQL Transport: No additional infrastructure needed
Performance gain: Leverages existing database investments
Real benefit: Use what you already have, get enterprise messaging
Real-World Example: For a multi-tenant e-commerce system, you might have separate databases for each tenant and use RabbitMQ for inter-service communication. This means each customer's data is completely isolated, but all services can communicate seamlessly for features like inventory updates, order processing, and notifications.
3. REST Client Services Configuration - Your Dependency Injection Powerhouse π
Why REST Client Configuration is Revolutionary π
Dependency Injection Ready: Services automatically registered and injectable
Configuration-Driven: No hardcoded service implementations
Testable by Design: Easy to mock and unit test
Environment Flexible: Different implementations per environment
Type-Safe: Strongly typed service contracts and configurations
What This Configuration Architecture Delivers β‘
Service Provider Pattern: Create configurable service providers for any external API
Automatic Registration: Services registered in DI container based on configuration
Interface-Based Design: Program against interfaces, not concrete implementations
Easy Testing: Mock services for unit and integration tests
Environment Switching: Different service implementations for Dev/Staging/Production
{
"RESTClientServices": {
"YourExternalService": {
"BaseUrl": "https://api.yourexternalservice.com",
"ApiKey": "YourApiKey",
"Timeout": "00:00:30"
},
"YourPaymentGateway": {
"BaseUrl": "https://api.paymentgateway.com",
"MerchantId": "YourMerchantId",
"SecretKey": "YourSecretKey"
}
}
}
Service Provider Architecture Deep Dive π
Configuration-Driven Service Creation ποΈ
What it does: Creates service providers based on configuration settings
Why powerful: No need to manually register each service
Real benefit: Add new external services by just adding configuration
Dependency Injection Integration π
What it does: Automatically registers services in the DI container
Why essential: Services become injectable throughout your application
Real benefit: Clean, testable, and maintainable code
Interface-Based Design π―
What it does: Services implement well-defined interfaces
Why important: Loose coupling and easy testing
Real benefit: Switch implementations without changing consuming code
How to Create Your Own Service Providers π οΈ
Step 1: Define Your Service Interface
public interface IYourExternalService
{
Task<YourResponse> GetDataAsync(string id);
Task<YourResponse> PostDataAsync(YourRequest request);
}
Step 2: Create Your Service Implementation
public class YourExternalService : IYourExternalService
{
private readonly HttpClient _httpClient;
private readonly YourServiceConfig _config;
public YourExternalService(HttpClient httpClient, IOptions<YourServiceConfig> config)
{
_httpClient = httpClient;
_config = config.Value;
}
public async Task<YourResponse> GetDataAsync(string id)
{
// Implementation using _httpClient and _config
}
}
Step 3: Register in DI Container
// In your Program.cs or Startup.cs
builder.Services.Configure<YourServiceConfig>(
builder.Configuration.GetSection("RESTClientServices:YourExternalService"));
builder.Services.AddHttpClient<IYourExternalService, YourExternalService>();
Step 4: Inject and Use
public class YourBusinessService
{
private readonly IYourExternalService _externalService;
public YourBusinessService(IYourExternalService externalService)
{
_externalService = externalService;
}
public async Task ProcessData()
{
var data = await _externalService.GetDataAsync("some-id");
// Process the data
}
}
Configuration Deep Dive π
BaseUrl - Your Service Endpoint π―
What it does: Defines where your external service lives
Why important: Different URLs for different environments
Real benefit: Same code works in Dev (sandbox) and Production (live)
ApiKey/SecretKey - Your Security Credentials π
What it does: Authenticates your application with external services
Why secure: Never hardcode these in your application
Real benefit: Rotate keys without code changes
Timeout - Your Performance Guardian β±οΈ
What it does: Prevents your app from hanging on slow external calls
Why important: External services can be slow or unresponsive
Real benefit: Your users never wait more than 30 seconds for anything
Real-World Service Provider Examples π
Payment Service Provider
public interface IPaymentService
{
Task<PaymentResult> ProcessPaymentAsync(PaymentRequest request);
Task<RefundResult> ProcessRefundAsync(RefundRequest request);
}
// Configuration automatically injects Stripe, PayPal, or Square implementations
Email Service Provider
public interface IEmailService
{
Task SendEmailAsync(EmailMessage message);
Task SendBulkEmailAsync(List<EmailMessage> messages);
}
// Configuration automatically injects SendGrid, Mailgun, or AWS SES implementations
Storage Service Provider
public interface IStorageService
{
Task<string> UploadFileAsync(Stream file, string fileName);
Task<Stream> DownloadFileAsync(string fileName);
}
// Configuration automatically injects AWS S3, Azure Blob, or Google Cloud implementations
Pro Tip: This configuration pattern makes it incredibly easy to add new external services. Just define the interface, create the implementation, add configuration, and register in DI. The FlexBase framework handles the rest, making your services available throughout your application via dependency injection!
Environment-Specific Configurations - Your Deployment Strategy π
Development Environment - The Debugging Paradise π οΈ
Why Development Configuration is Your Best Friend π
See Everything: Every log, every detail, every step
Local Everything: No external dependencies to slow you down
Instant Feedback: Changes reflect immediately
Safe Testing: Can't break production from your dev machine
Learning Mode: Understand exactly how your app works
{
"Serilog": {
"MinimumLevel": {
"Default": "Verbose"
}
},
"FlexBase": {
"AppDbConnection": "Data Source=localhost;Initial Catalog=YourProject_Dev;Integrated Security=true;TrustServerCertificate=True",
"RabbitMqConnectionString": "amqp://guest:guest@localhost:5672"
}
}
Development Superpowers β‘
Verbose Logging: See every single operation your app performs
Local Database: No network latency, instant responses
Integrated Security: No password management headaches
Local Message Broker: Test messaging without cloud dependencies
Detailed Errors: Stack traces, variable values, execution paths
Real Developer Benefits π―
Faster Debugging: Find issues in seconds, not hours
Confident Changes: Test everything locally before deploying
Learning Experience: Understand your application's behavior
Zero Risk: Can't accidentally affect production data
Instant Gratification: See results immediately
Production Environment - The Performance Beast π
Why Production Configuration is Mission-Critical π―
User Experience: Every millisecond matters to your users
Security First: Protect your data and your customers
Reliability: Your app must work 24/7 without fail
Performance: Handle thousands of users simultaneously
Monitoring: Know what's happening when you're not watching
{
"Serilog": {
"MinimumLevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "Console"
},
{
"Name": "File",
"Args": {
"path": "/var/log/yourproject/log.txt"
}
}
]
},
"FlexBase": {
"AppDbConnection": "Data Source=YourProductionServer;Initial Catalog=YourProject_Prod;User ID=YourProdUser;Password=YourProdPassword;TrustServerCertificate=True",
"RabbitMqConnectionString": "amqp://YourProdUser:YourProdPassword@YourProductionRabbitMq:5672"
}
}
Production Superpowers π
Information Logging: Only log what matters for monitoring
Production Database: Optimized for performance and reliability
Secure Credentials: Encrypted passwords and connection strings
High Availability: Redundant systems and failover capabilities
Performance Monitoring: Track response times and resource usage
Real Business Benefits π°
Happy Customers: Fast, reliable application experience
Lower Costs: Efficient resource usage saves money
Security Compliance: Meet industry standards and regulations
Scalability: Handle growth without major changes
Peace of Mind: Know your app is running smoothly
Staging Environment - The Production Rehearsal π
Why Staging is Your Safety Net π‘οΈ
Production Mirror: Same configuration as production
Safe Testing: Test with real data without affecting users
Performance Validation: Ensure your app can handle the load
Integration Testing: Test with real external services
Deployment Practice: Perfect your deployment process
Staging Configuration Strategy π
Same as Production: Identical settings and performance
Test Data: Safe to experiment with real data
External Services: Use sandbox/test endpoints
Monitoring: Full monitoring and alerting setup
Backup Strategy: Test your disaster recovery procedures
Pro Tip: Your staging environment should be a perfect copy of production. This is where you catch issues before they reach your users. The small cost of maintaining staging saves you from expensive production incidents!
Endpoint Configuration Patterns - Your Application's Command Centers ποΈ
1. Web API Endpoint Configuration - The Public Face of Your Application π
Why Web API Configuration is Critical π―
First Impression: This is what your users interact with
Performance: Every millisecond counts for user experience
Security: Protect your API from attacks and misuse
Scalability: Handle traffic spikes without breaking
Developer Experience: Make it easy for other developers to use
What This Configuration Delivers β‘
Lightning-Fast APIs: Optimized for speed and efficiency
Bulletproof Security: Authentication, authorization, and protection
Auto-Documentation: Swagger/OpenAPI docs generated automatically
CORS Support: Work seamlessly with web applications
Error Handling: Graceful error responses with proper HTTP codes
Program.cs Structure - The Heart of Your API:
var builder = WebApplication.CreateBuilder(args);
// π― STEP 1: Configure FlexBase Host - The Foundation
builder.Host.ConfigureCommonHost(
new ConfigureEndPointHostParams
{
HostName = "YourProject.EndPoint.WebAPI", // β Your API's identity
Routes = YourNsbRouteConfig.GetRoute(), // β Message routing rules
SearchPattern = "YourProject*.dll" // β Auto-discover your assemblies
}
);
// π STEP 2: Add FlexBase Services - The Power Pack
builder.Services.AddFlexBaseAspNetCoreServices();
// π‘οΈ STEP 3: Configure Controllers - The Security Layer
builder.Services.AddControllers(config =>
{
config.Filters.Add<FlexStandardResponseFilter>(); // β Consistent responses
config.Filters.Add<FlexStandardExceptionFilter>(); // β Graceful error handling
});
// π STEP 4: Configure Swagger - The Documentation Magic
builder.Services.AddSwaggerGen(c =>
{
c.SchemaFilter<FlexSwaggerSchemaFilter>(); // β Auto-generate schemas
c.OperationFilter<FlexSwaggerStandardOperationFilter>(); // β Standard operations
});
// π STEP 5: Configure CORS - The Cross-Origin Bridge
builder.Services.AddCors(options =>
{
options.AddPolicy("YourCorsPolicy", builder =>
{
builder.AllowAnyOrigin() // β Allow all origins
.AllowAnyHeader() // β Allow all headers
.AllowAnyMethod() // β Allow all HTTP methods
.WithExposedHeaders("X-Pagination"); // β Expose pagination headers
});
});
var app = builder.Build();
// π STEP 6: Register FlexBase Service Provider - The Connection Hub
var serviceScope = app.Services.CreateScope();
var serviceProvider = serviceScope.ServiceProvider;
var flexHost = serviceProvider.GetRequiredService<IFlexHost>();
flexHost.SetServiceProvider(serviceProvider);
// π STEP 7: Configure Middleware Pipeline - The Request Journey
app.UseCors("YourCorsPolicy"); // β Handle cross-origin requests
app.UseSwagger(); // β Serve API documentation
app.UseSwaggerUI(); // β Interactive API explorer
app.UseSerilogRequestLogging(); // β Log every request
app.UseHttpsRedirection(); // β Force HTTPS for security
app.UseAuthorization(); // β Check user permissions
app.MapControllers(); // β Route requests to controllers
app.Run(); // β Start the magic! β¨
Configuration Breakdown - What Each Step Does π
Step 1: FlexBase Host Configuration ποΈ
HostName: Identifies your API in logs and monitoring
Routes: Tells the system how to route messages between services
SearchPattern: Automatically finds and loads your project assemblies
Step 2: FlexBase Services β‘
AddFlexBaseAspNetCoreServices(): Registers all FlexBase services
What you get: Dependency injection, logging, configuration, and more
Why it matters: One line gives you enterprise-grade functionality
Step 3: Controller Configuration π‘οΈ
FlexStandardResponseFilter: Ensures all responses follow the same format
FlexStandardExceptionFilter: Catches exceptions and returns proper HTTP codes
Why it matters: Consistent API behavior and better error handling
Step 4: Swagger Configuration π
Auto-generated documentation: Your API documents itself
Interactive testing: Developers can test your API in the browser
Why it matters: Saves hours of manual documentation work
Step 5: CORS Configuration π
Cross-Origin Resource Sharing: Allows web apps to call your API
Security: Only allows requests from approved origins
Why it matters: Essential for modern web applications
Step 6: Service Provider Registration π
Dependency Injection: Makes services available throughout your app
FlexBase Integration: Connects your app to the FlexBase ecosystem
Why it matters: Enables all the FlexBase magic to work
Step 7: Middleware Pipeline π
Request Processing: Each request goes through this pipeline
Order matters: Middleware executes in the order you add it
Why it matters: Controls how requests are processed and responses are sent
Pro Tip: This configuration gives you a production-ready API in minutes. The FlexBase framework handles all the complex stuff, so you can focus on your business logic!
2. Message Handler Endpoint Configuration - The Command Processing Engine βοΈ
Why Message Handlers are Game-Changers π
Asynchronous Processing: Handle commands without blocking your API
Reliability: Messages are persisted and retried if they fail
Scalability: Process thousands of commands per second
Decoupling: Services communicate without knowing about each other
Resilience: System continues working even if some handlers fail
What This Configuration Enables β‘
Command Processing: Handle Create, Update, Delete operations
Background Tasks: Process long-running operations
Event Sourcing: Track all changes to your data
Microservices: Break your app into independent services
Eventual Consistency: Data becomes consistent over time
Program.cs Structure - The Command Center:
Console.Title = "YourProject.EndPoint.Handlers.Default";
// ποΈ STEP 1: Create Host Builder - The Foundation
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureCommonHost(
new ConfigureEndPointHostParams
{
HostName = "YourProject.EndPoint.Handlers.Default", // β Handler identity
Routes = YourNsbRouteConfig.GetRoute(), // β Message routing
SearchPattern = "YourProject*.dll" // β Auto-discovery
}
)
.ConfigureServices((hostingContext, services) =>
{
services.AddHostedService<YourWorker>(); // β Background worker
})
.Build();
// π STEP 2: Register FlexBase Services - The Power Connection
var serviceScope = host.Services.CreateScope();
var serviceProvider = serviceScope.ServiceProvider;
var flexHost = serviceProvider.GetRequiredService<IFlexHost>();
flexHost.SetServiceProvider(serviceProvider);
// π STEP 3: Start Processing - The Magic Begins
await host.RunAsync();
Message Handler Deep Dive π
What Happens Behind the Scenes π
Message Arrives: Command comes in via message bus
Handler Activates: Your handler processes the command
Business Logic: Execute your domain logic
Database Update: Save changes to database
Event Published: Notify other services of changes
Success Confirmed: Message marked as processed
Real-World Benefits π°
User Experience: API responds instantly, processing happens in background
Reliability: If processing fails, message is retried automatically
Scalability: Add more handlers to handle more load
Maintainability: Each handler has one responsibility
3. Event Subscriber Endpoint Configuration - The Event Processing Powerhouse π‘
Why Event Subscribers are Essential π―
Real-Time Updates: React to changes as they happen
System Integration: Connect different parts of your system
Audit Trail: Track every change for compliance
Notifications: Send emails, SMS, push notifications
Data Synchronization: Keep different systems in sync
What This Configuration Delivers β‘
Event Processing: Handle OrderCreated, UserRegistered, PaymentProcessed events
Cross-Service Communication: Services talk to each other via events
Business Workflows: Implement complex business processes
Integration Points: Connect with external systems
Analytics: Track user behavior and system performance
Program.cs Structure - The Event Hub:
Console.Title = "YourProject.EndPoint.Subscribers.Default";
// ποΈ STEP 1: Create Host Builder - The Event Foundation
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureCommonHost(
new ConfigureEndPointHostParams
{
HostName = "YourProject.EndPoint.Subscribers.Default", // β Subscriber identity
Routes = YourNsbRouteConfig.GetRoute(), // β Event routing
SearchPattern = "YourProject*.dll" // β Auto-discovery
}
)
.ConfigureServices((hostingContext, services) =>
{
services.AddHostedService<YourEventWorker>(); // β Event worker
})
.Build();
// π STEP 2: Register FlexBase Services - The Event Connection
var serviceScope = host.Services.CreateScope();
var serviceProvider = serviceScope.ServiceProvider;
var flexHost = serviceProvider.GetRequiredService<IFlexHost>();
flexHost.SetServiceProvider(serviceProvider);
// π STEP 3: Start Listening - The Event Magic Begins
await host.RunAsync();
Event Subscriber Deep Dive π
What Happens When Events Occur π
Event Published: Something changes in your system
Event Routed: Message bus routes event to subscribers
Subscriber Activates: Your subscriber processes the event
Business Logic: Execute your event handling logic
Side Effects: Send emails, update other systems, etc.
Event Acknowledged: Event marked as processed
Real-World Examples π
OrderCreated β Send confirmation email, reserve inventory
UserRegistered β Send welcome email, create user profile
PaymentProcessed β Update order status, send receipt
InventoryLow β Send alert to warehouse, reorder stock
Pro Tip: Event subscribers are perfect for implementing the "fire and forget" pattern. Your API can publish an event and continue processing, while subscribers handle the side effects asynchronously. This makes your system more responsive and resilient!
Configuration Best Practices - Your Path to Excellence π
1. Security Considerations - Protect What Matters Most π‘οΈ
Why Security is Non-Negotiable π
Data Breaches Cost Millions: Average cost is $4.45 million per incident
Regulatory Compliance: GDPR, HIPAA, SOX require proper data protection
Customer Trust: One breach can destroy years of trust
Legal Liability: Improper security can lead to lawsuits
Business Continuity: Security incidents can shut down your business
Security Best Practices β‘
Never commit sensitive data to source control
Why: Source control is not secure for secrets
How: Use .gitignore and environment variables
Benefit: Prevents accidental exposure of credentials
Use User Secrets for development
Why: Keep secrets out of your code
How:
dotnet user-secrets set "ConnectionStrings:Default" "your-connection"
Benefit: Secure development without configuration files
Use Azure Key Vault or similar for production
Why: Enterprise-grade secret management
How: Store all secrets in Key Vault, reference by name
Benefit: Centralized, auditable, and secure secret management
Rotate credentials regularly
Why: Compromised credentials become useless
How: Set up automatic rotation policies
Benefit: Minimize impact of credential compromise
2. Environment Management - Scale with Confidence π
Why Environment Management is Critical π―
Consistency: Same behavior across all environments
Predictability: Know what will happen in production
Efficiency: Deploy faster with fewer surprises
Quality: Catch issues before they reach users
Compliance: Meet audit and regulatory requirements
Environment Management Best Practices β‘
Separate configurations for each environment
Why: Different environments have different needs
How: Use environment-specific configuration files
Benefit: Optimize each environment for its purpose
Use environment variables for sensitive settings
Why: More secure than configuration files
How: Override configuration with environment variables
Benefit: Secrets never touch the file system
Validate configurations at startup
Why: Catch configuration errors early
How: Add validation logic to your startup code
Benefit: Fail fast with clear error messages
Document configuration requirements
Why: Help team members understand what's needed
How: Create configuration documentation and examples
Benefit: Faster onboarding and fewer configuration errors
3. Performance Optimization - Speed That Sells π
Why Performance Matters π°
User Experience: 1 second delay = 7% reduction in conversions
Search Rankings: Google uses page speed as a ranking factor
Server Costs: Efficient code uses fewer resources
Scalability: Fast code handles more users
Competitive Advantage: Speed is a differentiator
Performance Best Practices β‘
Connection pooling for database connections
Why: Reusing connections is much faster
How: Configure connection pool settings
Benefit: 10x faster database operations
Appropriate log levels for each environment
Why: Logging impacts performance
How: Verbose in dev, Information in production
Benefit: Better performance without losing visibility
Caching strategies for frequently accessed data
Why: Memory is faster than database
How: Use Redis, in-memory cache, or CDN
Benefit: Sub-millisecond response times
Resource monitoring and alerting
Why: Know when performance degrades
How: Set up performance counters and alerts
Benefit: Proactive performance management
4. Maintenance - Keep Your System Healthy π₯
Why Maintenance is Essential π§
Prevent Issues: Fix problems before they become critical
Improve Performance: Continuous optimization
Stay Current: Keep up with framework updates
Reduce Technical Debt: Clean up over time
Team Productivity: Well-maintained systems are easier to work with
Maintenance Best Practices β‘
Version control configuration changes
Why: Track what changed and when
How: Use Git for all configuration files
Benefit: Easy rollback and change tracking
Backup configurations before changes
Why: Quick recovery if something goes wrong
How: Create backups before major changes
Benefit: Peace of mind during updates
Test configurations in non-production environments
Why: Catch issues before they affect users
How: Deploy to staging first
Benefit: Confident production deployments
Document configuration dependencies
Why: Help team members understand relationships
How: Create dependency diagrams and documentation
Benefit: Easier troubleshooting and maintenance
Common Configuration Issues - Your Troubleshooting Guide π§
1. Connection String Issues - The Database Connection Blues πΎ
Why Connection Issues Happen π€
Typos: One wrong character breaks everything
Network Issues: Firewalls, DNS, routing problems
Authentication: Wrong username, password, or permissions
SSL/TLS: Certificate and encryption problems
Connection String Troubleshooting π
Invalid credentials - Verify username and password
Symptom: "Login failed" or "Authentication failed"
Solution: Double-check username and password
Prevention: Use connection string testing tools
Network connectivity - Check firewall and network settings
Symptom: "Connection timeout" or "Network unreachable"
Solution: Check firewall rules and network connectivity
Prevention: Document network requirements
Database permissions - Ensure user has required permissions
Symptom: "Access denied" or "Permission denied"
Solution: Grant appropriate database permissions
Prevention: Use least-privilege principle
SSL/TLS settings - Configure TrustServerCertificate appropriately
Symptom: "SSL connection error" or "Certificate validation failed"
Solution: Set TrustServerCertificate=True for development
Prevention: Use proper certificates in production
2. Message Bus Configuration - The Communication Breakdown π‘
Why Message Bus Issues Occur π€
Service Unavailable: Message broker is down or unreachable
Configuration Mismatch: Wrong routing or endpoint settings
Serialization Problems: Messages can't be serialized/deserialized
Permission Issues: Insufficient access to message broker
Message Bus Troubleshooting π
Transport connectivity - Verify message broker is running
Symptom: "Connection refused" or "Service unavailable"
Solution: Check if RabbitMQ, SQL Server, or Azure Service Bus is running
Prevention: Set up health checks and monitoring
Routing configuration - Check NsbRouteConfig settings
Symptom: Messages not reaching handlers
Solution: Verify routing configuration and endpoint names
Prevention: Use configuration validation
Persistence settings - Ensure persistence database is accessible
Symptom: "Database connection failed" in message processing
Solution: Check persistence database connection string
Prevention: Test persistence database connectivity
Serialization issues - Verify message serialization settings
Symptom: "Serialization error" or "Type not found"
Solution: Check message contracts and serialization settings
Prevention: Use version-tolerant serialization
3. Logging Configuration - The Silent System Problem π
Why Logging Issues Matter π€
Debugging Nightmare: Can't see what's happening
Performance Impact: Too much logging slows down the system
Storage Issues: Log files filling up disk space
Security Concerns: Sensitive data in logs
Logging Troubleshooting π
File permissions - Ensure log directory is writable
Symptom: "Access denied" when writing logs
Solution: Check directory permissions and ownership
Prevention: Set up proper directory permissions
Disk space - Monitor log file sizes and retention
Symptom: "No space left on device" or slow performance
Solution: Implement log rotation and retention policies
Prevention: Monitor disk usage and set up alerts
Performance impact - Balance logging detail with performance
Symptom: Slow application performance
Solution: Reduce log level or optimize logging configuration
Prevention: Test performance impact of logging changes
Log aggregation - Configure centralized logging if needed
Symptom: Difficult to correlate logs across services
Solution: Use centralized logging like ELK stack or Azure Monitor
Prevention: Plan for log aggregation from the start
Conclusion - Your Configuration Success Story π
What You've Accomplished π
Mastered FlexBase Configuration: You now understand the power of centralized configuration
Learned Security Best Practices: Your applications will be secure and compliant
Optimized for Performance: Your applications will be fast and scalable
Built for Maintenance: Your configurations will be easy to manage and update
The Value You've Gained π
Developer Productivity: Spend less time on configuration, more on business logic
System Reliability: Robust configurations that work in all environments
Security Confidence: Know your data and systems are protected
Performance Excellence: Applications that scale and perform beautifully
Operational Peace of Mind: Systems that are easy to monitor and maintain
Your Next Steps π
Apply These Patterns: Use this guide to configure your FlexBase applications
Customize for Your Domain: Adapt the examples to your specific business needs
Share with Your Team: Help your colleagues benefit from these best practices
Keep Learning: Stay updated with FlexBase framework improvements
Contribute Back: Share your own configuration discoveries with the community
Remember: Great configuration is the foundation of great applications. With the patterns and practices in this guide, you're well-equipped to build robust, scalable, and maintainable FlexBase applications that will serve your business for years to come! π
Last updated