Marventa.Framework 2.4.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Marventa.Framework --version 2.4.0
                    
NuGet\Install-Package Marventa.Framework -Version 2.4.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Marventa.Framework" Version="2.4.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Marventa.Framework" Version="2.4.0" />
                    
Directory.Packages.props
<PackageReference Include="Marventa.Framework" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Marventa.Framework --version 2.4.0
                    
#r "nuget: Marventa.Framework, 2.4.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Marventa.Framework@2.4.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Marventa.Framework&version=2.4.0
                    
Install as a Cake Addin
#tool nuget:?package=Marventa.Framework&version=2.4.0
                    
Install as a Cake Tool

🚀 Marventa Framework

.NET License NuGet

Complete enterprise-grade .NET framework with 40+ modular features including file management, security, multi-tenancy, messaging, analytics, e-commerce, and more

📋 Table of Contents

  1. Quick Start

  2. Available Features

  3. Core Philosophy

  4. Architecture

  5. Features 🗄️ File & Storage

    🔐 Security & Authentication

    🏢 Multi-Tenancy & Architecture

    ⚡ Performance & Scalability

    📊 Analytics & Monitoring

    📧 Messaging & Communication

    🔍 Search & AI/ML

    ⏱️ Background & Data Processing

    🛒 E-Commerce & Business

    🌐 API & Web Management

    ⚙️ Configuration & Features

  6. Configuration

  7. Testing

  8. Best Practices


⚡ Quick Start

Installation

dotnet add package Marventa.Framework

Basic Setup

// Program.cs
using Marventa.Framework.Web.Extensions;

var builder = WebApplication.CreateBuilder(args);

// ⚡ MINIMAL SETUP - Only enable what you need!
// All features are FALSE by default - just enable what you want to use
builder.Services.AddMarventaFramework(options =>
{
    // 🗄️ Basic file operations
    options.EnableStorage = true;          // Storage Management
    options.EnableFileProcessor = true;    // Image Processing

    // 🔐 Basic security (recommended for production)
    options.EnableSecurity = true;         // Basic Security & Authentication
    options.EnableValidation = true;       // Input Validation

    // That's it! All other features are disabled by default.
    // Enable additional features as needed:

    // options.EnableJWT = true;           // JWT Authentication
    // options.EnableCaching = true;       // Performance boost
    // options.EnableEmail = true;         // Email notifications
    // options.EnableMultiTenancy = true;  // Multi-tenant apps
    // options.EnableECommerce = true;     // E-commerce features
});

// 🎯 PRODUCTION-READY SETUP - Common production features
builder.Services.AddMarventaFramework(options =>
{
    // Core features
    options.EnableStorage = true;
    options.EnableFileProcessor = true;
    options.EnableSecurity = true;
    options.EnableJWT = true;

    // Performance & monitoring
    options.EnableCaching = true;
    options.EnableRateLimiting = true;
    options.EnableHealthChecks = true;
    options.EnableLogging = true;

    // API management
    options.EnableValidation = true;
    options.EnableExceptionHandling = true;
    options.EnableHttpClient = true;
});

// 🚀 ENTERPRISE SETUP - All advanced features
builder.Services.AddMarventaFramework(options =>
{
    // Enable everything you need for enterprise applications
    options.EnableStorage = true;
    options.EnableFileProcessor = true;
    options.EnableCDN = true;
    options.EnableMetadata = true;

    options.EnableSecurity = true;
    options.EnableJWT = true;
    options.EnableApiKeys = true;
    options.EnableEncryption = true;

    options.EnableMultiTenancy = true;
    options.EnableEventDriven = true;
    options.EnableCQRS = true;
    options.EnableRepository = true;

    options.EnableCaching = true;
    options.EnableRateLimiting = true;
    options.EnableDistributedLocking = true;
    options.EnableIdempotency = true;

    options.EnableAnalytics = true;
    options.EnableHealthChecks = true;
    options.EnableObservability = true;
    options.EnableLogging = true;

    options.EnableMessaging = true;
    options.EnableEmail = true;
    options.EnableSMS = true;

    options.EnableSearch = true;
    options.EnableML = true;

    options.EnableBackgroundJobs = true;
    options.EnableDatabaseSeeding = true;
    options.EnableProjections = true;

    options.EnableECommerce = true;
    options.EnablePayments = true;
    options.EnableShipping = true;
    options.EnableFraudDetection = true;

    options.EnableVersioning = true;
    options.EnableHttpClient = true;
    options.EnableExceptionHandling = true;
    options.EnableValidation = true;

    options.EnableFeatureFlags = true;
});

var app = builder.Build();
app.UseMarventaFramework();
app.Run();

Simple File Upload

[ApiController]
public class FilesController : ControllerBase
{
    private readonly IMarventaStorage _storage;
    private readonly IMarventaFileProcessor _processor;

    public async Task<IActionResult> UploadImage(IFormFile file)
    {
        // Process image
        var processResult = await _processor.ProcessImageAsync(file.OpenReadStream(), new()
        {
            Width = 800, Height = 600, Quality = 85
        });

        // Upload to storage
        var uploadResult = await _storage.UploadFileAsync(
            processResult.ProcessedImage, file.FileName, file.ContentType);

        return Ok(new {
            FileId = uploadResult.FileId,
            Url = uploadResult.PublicUrl
        });
    }
}

🎛️ Available Features

47 modular features - enable only what you need!

🗄️ File & Storage (4 features)

options.EnableStorage = true;          // Multi-provider storage (Azure, AWS, Local)
options.EnableFileProcessor = true;    // Image processing & optimization
options.EnableCDN = true;             // Content delivery networks
options.EnableMetadata = true;        // File metadata management

🔐 Security & Authentication (4 features)

options.EnableSecurity = true;        // Basic security framework
options.EnableJWT = true;             // JWT token management
options.EnableApiKeys = true;         // API key authentication
options.EnableEncryption = true;      // Data encryption services

🏢 Multi-Tenancy & Architecture (5 features)

options.EnableMultiTenancy = true;    // Complete tenant isolation
options.EnableEventDriven = true;     // Domain & integration events
options.EnableCQRS = true;            // Command Query separation
options.EnableSagas = true;           // Long-running processes
options.EnableRepository = true;      // Data access abstraction

⚡ Performance & Scalability (5 features)

options.EnableCaching = true;         // Distributed caching
options.EnableRateLimiting = true;    // API protection
options.EnableDistributedLocking = true; // Critical section locks
options.EnableIdempotency = true;     // Safe operation retries
options.EnableCircuitBreaker = true;  // Circuit breaker pattern

📊 Analytics & Monitoring (5 features)

options.EnableAnalytics = true;       // Event & metric tracking
options.EnableHealthChecks = true;    // System health monitoring
options.EnableObservability = true;   // Distributed tracing
options.EnableLogging = true;         // Structured logging
options.EnableTracking = true;        // Advanced tracking features

📧 Messaging & Communication (4 features)

options.EnableMessaging = true;       // Message bus integration
options.EnableEmail = true;           // Email notifications
options.EnableSMS = true;             // SMS notifications
options.EnableDeadLetterQueue = true; // Dead letter queue handling

🔍 Search & AI/ML (2 features)

options.EnableSearch = true;          // Elasticsearch integration
options.EnableML = true;              // AI/ML content analysis

⏱️ Background & Data Processing (5 features)

options.EnableBackgroundJobs = true;  // Job scheduling
options.EnableDatabaseSeeding = true; // Database initialization
options.EnableProjections = true;     // Event sourcing projections
options.EnableRealTimeProjections = true; // Real-time projection updates
options.EnableSeeding = true;         // Advanced data seeding

🛒 E-Commerce & Business (4 features)

options.EnableECommerce = true;       // E-commerce framework
options.EnablePayments = true;        // Payment processing
options.EnableShipping = true;        // Shipping management
options.EnableFraudDetection = true;  // Fraud prevention

🌐 API & Web Management (4 features)

options.EnableVersioning = true;      // API versioning
options.EnableHttpClient = true;      // HTTP client abstraction
options.EnableExceptionHandling = true; // Global error handling
options.EnableValidation = true;      // Input validation

⚙️ Configuration & Features (1 feature)

options.EnableFeatureFlags = true;    // Dynamic feature toggles

📊 Feature Count Summary

  • Total Features: 47
  • File & Storage: 4 features
  • Security: 4 features
  • Architecture: 5 features
  • Performance: 5 features
  • Monitoring: 5 features
  • Communication: 4 features
  • Search & AI: 2 features
  • Background: 5 features
  • E-Commerce: 4 features
  • API Management: 4 features
  • Configuration: 1 feature

💡 Smart Defaults

  • All features are FALSE by default
  • Minimal setup: Just enable 3-4 core features
  • Production setup: Enable 8-10 essential features
  • Enterprise setup: Enable all 47 features you need

🎯 Core Philosophy

  • 💡 Smart Defaults: All features are FALSE by default - just enable what you need!
  • 🔧 True Modularity: Pay only for what you use - unused features add zero overhead
  • 🎯 Three Setup Levels: Minimal (3 features) → Production (9 features) → Enterprise (47 features)
  • 🔄 Provider Agnostic: Switch providers without code changes
  • ⚡ Performance First: Async operations and optimized processing
  • 🏢 Enterprise Ready: Production-tested with comprehensive error handling
  • 👨‍💻 Developer Friendly: Clean APIs with extensive documentation

🏗️ Architecture

Clean, modular architecture with 47 enterprise features in 29+ focused, single-responsibility files:

Marventa.Framework/
├── 📦 Core/                    # Domain models and interfaces
│   ├── 🔌 Interfaces/         # 40+ service contracts
│   ├── 📄 Models/            # 29+ focused model files
│   │   ├── CDN/              # 8 CDN-specific files
│   │   ├── Storage/          # 12 Storage-specific files
│   │   ├── ML/               # 6 ML-specific files
│   │   ├── FileProcessing/   # Processing models
│   │   └── FileMetadata/     # 3 Metadata files
│   ├── 🔐 Security/          # JWT, Encryption, API Keys
│   ├── 🏢 Multi-Tenant/      # Tenant management
│   ├── 🔄 Events/            # Domain & Integration events
│   └── 🚫 Exceptions/        # Custom exceptions
├── 🎯 Domain/                  # Business logic
│   └── 🛒 ECommerce/         # Payment, Shipping, Fraud
├── 🔧 Application/            # CQRS, Commands, Queries
│   ├── ⚡ Commands/          # Command handlers
│   ├── 🔍 Queries/           # Query handlers
│   ├── 🔄 Behaviors/         # MediatR behaviors
│   └── ✅ Validators/        # Validation logic
├── 🏗️ Infrastructure/         # Service implementations
│   ├── 📧 Messaging/         # Email, SMS, Message Bus
│   ├── 🔍 Search/            # Elasticsearch
│   ├── 📊 Analytics/         # Event tracking
│   ├── ⚡ RateLimiting/       # Tenant rate limits
│   └── 🔍 Observability/     # Distributed tracing
└── 🌐 Web/                   # ASP.NET integration
    ├── 🔐 Security/          # Middleware
    ├── 📋 Middleware/        # Exception, Correlation
    ├── 📊 Versioning/        # API versioning
    └── ⚙️ Extensions/        # DI configuration

SOLID Compliance: Each file follows Single Responsibility Principle


🎨 Features

🗄️ Storage Management

Multi-provider storage with unified API

// Azure Blob Storage
services.AddMarventaFramework(options =>
{
    options.StorageOptions.Provider = StorageProvider.AzureBlob;
    options.StorageOptions.ConnectionString = "DefaultEndpointsProtocol=https;...";
});

// AWS S3
options.StorageOptions.Provider = StorageProvider.AWS;
options.StorageOptions.AccessKey = "your-access-key";
options.StorageOptions.SecretKey = "your-secret-key";

// Local File System
options.StorageOptions.Provider = StorageProvider.LocalFile;
options.StorageOptions.BasePath = "uploads";

Usage Examples:

// Upload file
var result = await _storage.UploadFileAsync(stream, "document.pdf", "application/pdf");

// Download file
var download = await _storage.DownloadFileAsync(result.FileId);

// File operations
await _storage.CopyFileAsync(fileId, "backup/document.pdf");
await _storage.DeleteFileAsync(fileId);

// Bulk operations
var files = new Dictionary<string, Stream> { ["file1.jpg"] = stream1, ["file2.png"] = stream2 };
var bulkResult = await _storage.BulkUploadAsync(files);

🖼️ Image Processing

Comprehensive image manipulation and optimization

// Image processing configuration
options.FileProcessorOptions.Provider = FileProcessorProvider.ImageSharp;
options.FileProcessorOptions.DefaultImageQuality = 85;
options.FileProcessorOptions.MaxFileSizeBytes = 52428800; // 50MB

Usage Examples:

// Resize image
var resizeResult = await _processor.ProcessImageAsync(imageStream, new ProcessingOptions
{
    Width = 800,
    Height = 600,
    Quality = 90
});

// Generate thumbnails
var thumbnailResult = await _processor.GenerateThumbnailsAsync(imageStream, new[]
{
    new ThumbnailSize { Name = "small", Width = 150, Height = 150 },
    new ThumbnailSize { Name = "medium", Width = 300, Height = 300 },
    new ThumbnailSize { Name = "large", Width = 600, Height = 600 }
});

// Optimize image
var optimizeResult = await _processor.OptimizeImageAsync(imageStream, new OptimizationOptions
{
    Quality = 75,
    EnableProgressive = true,
    PreserveMetadata = false
});

// Apply watermark
var watermarkResult = await _processor.ApplyWatermarkAsync(imageStream, new WatermarkOptions
{
    Text = "© 2024 Company Name",
    Position = WatermarkPosition.BottomRight,
    Opacity = 0.7f
});

// Convert format
var convertResult = await _processor.ConvertFormatAsync(imageStream, "webp", new ConversionOptions
{
    Quality = 80,
    PreserveMetadata = true
});

🌐 CDN Integration

Global content delivery with caching

// CDN configuration
options.CDNOptions.Provider = CDNProvider.CloudFlare;
options.CDNOptions.Endpoint = "https://cdn.example.com";
options.CDNOptions.ApiKey = "your-api-key";
options.CDNOptions.DefaultCacheTTL = 86400; // 24 hours

Usage Examples:

// Upload to CDN
var cdnResult = await _cdn.UploadToCDNAsync(fileId, fileStream, "image/jpeg", new CDNUploadOptions
{
    CacheTTL = TimeSpan.FromHours(24),
    EnableCompression = true
});

// Invalidate cache
await _cdn.InvalidateCacheAsync(new[] { "/images/photo.jpg", "/css/style.css" });

// Transform images on CDN
var transformResult = await _cdn.TransformImageAsync(fileId, new ImageTransformation
{
    Width = 400,
    Height = 300,
    Quality = 80,
    Format = "webp"
});

// Get CDN metrics
var metrics = await _cdn.GetCDNMetricsAsync(new TimeRange
{
    StartTime = DateTime.UtcNow.AddDays(-30),
    EndTime = DateTime.UtcNow
});

🤖 AI/ML Services

Intelligent content analysis and processing

// ML configuration
options.MLOptions.Provider = MLProvider.AzureAI;
options.MLOptions.ApiEndpoint = "https://cognitiveservices.azure.com";
options.MLOptions.ApiKey = "your-api-key";
options.MLOptions.MinConfidenceThreshold = 0.7;

Usage Examples:

// Image analysis
var analysisResult = await _ml.AnalyzeImageAsync(imageStream, new ImageAnalysisOptions
{
    DetectObjects = true,
    DetectFaces = true,
    GenerateTags = true,
    ExtractText = true
});

// Face detection
var faceResult = await _ml.DetectFacesAsync(imageStream, new FaceDetectionOptions
{
    DetectAge = true,
    DetectGender = true,
    DetectEmotions = true
});

// Text extraction (OCR)
var ocrResult = await _ml.ExtractTextAsync(imageStream, new TextExtractionOptions
{
    Language = "en",
    DetectOrientation = true
});

// Content optimization suggestions
var suggestions = await _ml.GetOptimizationSuggestionsAsync(fileId, new OptimizationRequest
{
    TargetAudience = "mobile",
    MaxFileSize = 1024000 // 1MB
});

📊 Metadata Management

Advanced file metadata and search capabilities

// Metadata configuration
options.MetadataOptions.Provider = MetadataProvider.MongoDB;
options.MetadataOptions.ConnectionString = "mongodb://localhost:27017";
options.MetadataOptions.DatabaseName = "FileMetadata";

Usage Examples:

// Add file metadata
var metadata = new FileMetadata
{
    FileId = fileId,
    Title = "Product Image",
    Description = "High-quality product photo",
    Tags = new[] { new FileTag { Name = "product", Source = TagSource.Manual } },
    CustomProperties = new Dictionary<string, object>
    {
        ["ProductId"] = "P12345",
        ["Category"] = "Electronics"
    }
};
await _metadata.AddFileMetadataAsync(metadata);

// Search files
var searchResult = await _metadata.SearchFilesAsync(new MetadataSearchOptions
{
    Query = "product electronics",
    FileTypes = new[] { "image/jpeg", "image/png" },
    DateRange = new TimeRange(DateTime.Now.AddDays(-30), DateTime.Now),
    Tags = new[] { "product" }
});

// File analytics
var analytics = await _metadata.GetFileAnalyticsAsync(fileId);
Console.WriteLine($"Views: {analytics.TotalViews}, Downloads: {analytics.TotalDownloads}");

// Tag management
await _metadata.AddTagsToFileAsync(fileId, new[] { "featured", "bestseller" });
var popularTags = await _metadata.GetPopularTagsAsync(new TagPopularityOptions
{
    TimeRange = new TimeRange(DateTime.Now.AddDays(-30), DateTime.Now),
    Limit = 10
});

🔐 Security & Authentication

Comprehensive security with JWT, API Keys, and encryption

Enable/Disable Options:

// Enable all security features
services.AddMarventaFramework(options =>
{
    options.EnableSecurity = true;         // Basic Security & Authentication
    options.EnableJWT = true;              // JWT Token Management
    options.EnableApiKeys = true;          // API Key Authentication
    options.EnableEncryption = true;       // Encryption Services
});

// Or disable specific security features
services.AddMarventaFramework(options =>
{
    options.EnableSecurity = true;         // Keep basic security
    options.EnableJWT = false;             // Disable JWT if using external auth
    options.EnableApiKeys = true;          // Keep API keys
    options.EnableEncryption = false;      // Disable encryption for performance
});

Configuration:

// JWT Configuration
options.JwtOptions.SecretKey = "your-secret-key";
options.JwtOptions.Issuer = "your-app";
options.JwtOptions.Audience = "your-audience";
options.JwtOptions.ExpirationMinutes = 60;

Usage Examples:

// JWT Token Generation
var tokenResult = await _tokenService.GenerateTokenAsync(userId, new[] { "admin", "user" });
Console.WriteLine($"Access Token: {tokenResult.AccessToken}");
Console.WriteLine($"Refresh Token: {tokenResult.RefreshToken}");

// API Key Authentication (in controller)
[ApiKey]
public class SecureController : ControllerBase { }

// Encryption Service
var encrypted = await _encryptionService.EncryptAsync("sensitive-data");
var decrypted = await _encryptionService.DecryptAsync(encrypted);

// Password Hashing
var hash = await _encryptionService.GenerateHashAsync("password", salt);
var isValid = await _encryptionService.VerifyHashAsync("password", hash, salt);

🏢 Multi-Tenancy Support

Complete tenant isolation and management

Enable/Disable Options:

// Enable full multi-tenancy support
services.AddMarventaFramework(options =>
{
    options.EnableMultiTenancy = true;     // Multi-Tenancy Support
    options.EnableEventDriven = true;      // Event-Driven Architecture
    options.EnableCQRS = true;             // CQRS Pattern
    options.EnableSagas = true;            // Saga Pattern Management
    options.EnableRepository = true;       // Repository Pattern & Unit of Work
});

// Minimal setup without multi-tenancy
services.AddMarventaFramework(options =>
{
    options.EnableMultiTenancy = false;    // Single-tenant application
    options.EnableEventDriven = false;     // Simple CRUD operations
    options.EnableCQRS = false;            // Direct service calls
    options.EnableSagas = false;           // No long-running processes
    options.EnableRepository = true;       // Keep data access abstraction
});

Configuration:

// Multi-tenant configuration
options.MultiTenancyOptions.TenantResolutionStrategy = TenantResolutionStrategy.Header;
options.MultiTenancyOptions.DefaultTenantId = "default";
options.MultiTenancyOptions.EnableTenantScopedServices = true;

Usage Examples:

// Tenant Context
var currentTenant = _tenantContext.Current;
Console.WriteLine($"Current Tenant: {currentTenant.Id} - {currentTenant.Name}");

// Tenant-Scoped Caching
await _tenantScopedCache.SetAsync("key", data, TimeSpan.FromHours(1));
var cachedData = await _tenantScopedCache.GetAsync<MyData>("key");

// Tenant Rate Limiting
var isAllowed = await _tenantRateLimiter.TryAcquireAsync("api-endpoint", 100, TimeSpan.FromMinutes(1));
if (!isAllowed) return StatusCode(429, "Rate limit exceeded");

// Tenant Authorization
var hasAccess = await _tenantAuthorization.HasAccessAsync(tenantId, "feature-name");

🔄 Event-Driven Architecture

Domain and Integration events with Event Bus

// Event Bus configuration
options.EventBusOptions.Provider = EventBusProvider.RabbitMQ;
options.EventBusOptions.ConnectionString = "amqp://localhost";

Usage Examples:

// Publishing Domain Events
var domainEvent = new UserRegisteredEvent(userId, email, DateTime.UtcNow);
await _eventBus.PublishAsync(domainEvent);

// Publishing Integration Events
var integrationEvent = new OrderCompletedEvent(orderId, customerId, totalAmount);
await _eventBus.PublishIntegrationEventAsync(integrationEvent);

// Event Handler
public class UserRegisteredEventHandler : IDomainEventHandler<UserRegisteredEvent>
{
    public async Task HandleAsync(UserRegisteredEvent domainEvent)
    {
        // Send welcome email
        await _emailService.SendWelcomeEmailAsync(domainEvent.Email);
    }
}

⚡ CQRS Pattern

Command Query Responsibility Segregation with MediatR-style architecture

Usage Examples:

// Command Definition
public class CreateUserCommand : ICommand<CreateUserResult>
{
    public string Email { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

// Command Handler
public class CreateUserCommandHandler : ICommandHandler<CreateUserCommand, CreateUserResult>
{
    public async Task<CreateUserResult> HandleAsync(CreateUserCommand command)
    {
        // Create user logic
        var user = new User(command.Email, command.FirstName, command.LastName);
        await _userRepository.AddAsync(user);
        return new CreateUserResult { UserId = user.Id };
    }
}

// Query Definition
public class GetUserQuery : IQuery<UserDto>
{
    public int UserId { get; set; }
}

// Query Handler
public class GetUserQueryHandler : IQueryHandler<GetUserQuery, UserDto>
{
    public async Task<UserDto> HandleAsync(GetUserQuery query)
    {
        var user = await _userRepository.GetByIdAsync(query.UserId);
        return _mapper.Map<UserDto>(user);
    }
}

⚡ Performance & Scalability

Rate limiting, caching, and distributed locking

Enable/Disable Options:

// High-performance setup
services.AddMarventaFramework(options =>
{
    options.EnableCaching = true;          // Caching Services
    options.EnableRateLimiting = true;     // Rate Limiting
    options.EnableDistributedLocking = true; // Distributed Locking
    options.EnableIdempotency = true;      // Idempotency Support
});

// Simple setup without advanced performance features
services.AddMarventaFramework(options =>
{
    options.EnableCaching = false;         // No caching for simple apps
    options.EnableRateLimiting = false;    // No rate limiting
    options.EnableDistributedLocking = false; // Single instance deployment
    options.EnableIdempotency = false;     // Simple operations
});

// Production-ready but minimal
services.AddMarventaFramework(options =>
{
    options.EnableCaching = true;          // Basic caching
    options.EnableRateLimiting = true;     // Basic protection
    options.EnableDistributedLocking = false; // Single instance
    options.EnableIdempotency = true;      // Safe retries
});

Configuration:

// Caching configuration
options.CacheOptions.Provider = CacheProvider.Redis;
options.CacheOptions.ConnectionString = "localhost:6379";
options.CacheOptions.DefaultExpiration = TimeSpan.FromMinutes(30);

Usage Examples:

// Distributed Caching
await _cacheService.SetAsync("user:123", userData, TimeSpan.FromHours(1));
var cachedUser = await _cacheService.GetAsync<UserData>("user:123");

// Distributed Locking
using var lockHandle = await _distributedLock.AcquireAsync("resource-key", TimeSpan.FromMinutes(5));
if (lockHandle.IsAcquired)
{
    // Critical section - only one process can execute this
    await ProcessCriticalOperation();
}

// Rate Limiting Attribute
[RateLimit(RequestsPerMinute = 60)]
public class ApiController : ControllerBase { }

📊 Analytics & Monitoring

Comprehensive analytics and health monitoring

Enable/Disable Options:

// Full monitoring setup
services.AddMarventaFramework(options =>
{
    options.EnableAnalytics = true;        // Analytics & Monitoring
    options.EnableHealthChecks = true;     // Health Checks
    options.EnableObservability = true;    // Observability & Correlation
    options.EnableLogging = true;          // Logging Service
});

// Basic monitoring
services.AddMarventaFramework(options =>
{
    options.EnableAnalytics = false;       // No analytics tracking
    options.EnableHealthChecks = true;     // Basic health checks
    options.EnableObservability = false;   // No distributed tracing
    options.EnableLogging = true;          // Keep logging
});

// Development setup
services.AddMarventaFramework(options =>
{
    options.EnableAnalytics = false;       // No tracking in dev
    options.EnableHealthChecks = false;    // Not needed in dev
    options.EnableObservability = true;    // Debug tracing
    options.EnableLogging = true;          // Debug logging
});

Configuration:

// Analytics configuration
options.AnalyticsOptions.Provider = AnalyticsProvider.GoogleAnalytics;
options.AnalyticsOptions.TrackingId = "GA-123456789";

Usage Examples:

// Event Tracking
await _analyticsService.TrackEventAsync("user_action", "button_click", new
{
    UserId = userId,
    ButtonName = "purchase",
    PageUrl = "/checkout"
});

// Metric Tracking
await _analyticsService.TrackMetricAsync("response_time", 150.5, new
{
    Endpoint = "/api/users",
    Method = "GET"
});

// Exception Tracking
try { /* operation */ }
catch (Exception ex)
{
    await _analyticsService.TrackExceptionAsync(ex, new { UserId = userId });
}

// Health Checks
var healthStatus = await _healthCheck.CheckHealthAsync();
Console.WriteLine($"System Health: {healthStatus.Status}");
foreach (var check in healthStatus.Checks)
{
    Console.WriteLine($"  {check.Key}: {check.Value.Status}");
}

📧 Messaging & Communication

Email, SMS, and Message Bus integration

Enable/Disable Options:

// Full communication suite
services.AddMarventaFramework(options =>
{
    options.EnableMessaging = true;        // Message Bus
    options.EnableEmail = true;            // Email Service
    options.EnableSMS = true;              // SMS Service
});

// Email-only setup
services.AddMarventaFramework(options =>
{
    options.EnableMessaging = false;       // No message bus
    options.EnableEmail = true;            // Email notifications
    options.EnableSMS = false;             // No SMS
});

// Minimal setup (no external communication)
services.AddMarventaFramework(options =>
{
    options.EnableMessaging = false;       // No messaging
    options.EnableEmail = false;           // No email
    options.EnableSMS = false;             // No SMS
});

Configuration:

// Email configuration
options.EmailOptions.Provider = EmailProvider.SendGrid;
options.EmailOptions.ApiKey = "your-sendgrid-key";
options.EmailOptions.FromEmail = "noreply@yourapp.com";

Usage Examples:

// Email Service
await _emailService.SendEmailAsync(new EmailMessage
{
    To = "user@example.com",
    Subject = "Welcome!",
    HtmlBody = "<h1>Welcome to our platform!</h1>",
    PlainTextBody = "Welcome to our platform!"
});

// Bulk Email
var recipients = new[] { "user1@example.com", "user2@example.com" };
await _emailService.SendBulkEmailAsync(recipients, "Newsletter", htmlContent);

// SMS Service
await _smsService.SendSmsAsync("+1234567890", "Your verification code: 123456");

// Message Bus
await _messageBus.PublishAsync(new UserRegisteredMessage
{
    UserId = userId,
    Email = email,
    RegistrationDate = DateTime.UtcNow
});

🔍 Search & Discovery

Elasticsearch integration with advanced search capabilities

Enable/Disable Options:

// Enable search with AI/ML
services.AddMarventaFramework(options =>
{
    options.EnableSearch = true;           // Search & Discovery
    options.EnableML = true;               // AI/ML Services for enhanced search
});

// Basic app without search
services.AddMarventaFramework(options =>
{
    options.EnableSearch = false;          // No search functionality
    options.EnableML = false;              // No AI/ML features
});

// Search-only (no AI/ML)
services.AddMarventaFramework(options =>
{
    options.EnableSearch = true;           // Basic search
    options.EnableML = false;              // No AI/ML overhead
});

Configuration:

// Search configuration
options.SearchOptions.Provider = SearchProvider.Elasticsearch;
options.SearchOptions.ConnectionString = "http://localhost:9200";
options.SearchOptions.DefaultIndex = "documents";

Usage Examples:

// Document Indexing
var document = new ProductDocument
{
    Id = "prod-123",
    Name = "Wireless Headphones",
    Description = "High-quality wireless headphones",
    Price = 99.99m,
    Category = "Electronics"
};
await _searchService.IndexDocumentAsync("products", document);

// Search with Filters
var searchResult = await _searchService.SearchAsync<ProductDocument>("products", new SearchRequest
{
    Query = "wireless headphones",
    Filters = new Dictionary<string, object>
    {
        ["Category"] = "Electronics",
        ["Price"] = new { gte = 50, lte = 150 }
    },
    Sort = new[] { new SortField { Field = "Price", Order = SortOrder.Ascending } },
    Size = 20,
    From = 0
});

// Aggregations
var aggregationResult = await _searchService.AggregateAsync("products", new AggregationRequest
{
    Aggregations = new Dictionary<string, IAggregation>
    {
        ["avg_price"] = new AverageAggregation { Field = "Price" },
        ["categories"] = new TermsAggregation { Field = "Category" }
    }
});

⏱️ Background Processing

Job scheduling and background task management

Enable/Disable Options:

// Full background processing suite
services.AddMarventaFramework(options =>
{
    options.EnableBackgroundJobs = true;   // Background Processing
    options.EnableDatabaseSeeding = true;  // Database Seeding
    options.EnableProjections = true;      // Projections (Event Sourcing)
});

// Simple app without background processing
services.AddMarventaFramework(options =>
{
    options.EnableBackgroundJobs = false;  // No background jobs
    options.EnableDatabaseSeeding = true;  // Keep seeding for setup
    options.EnableProjections = false;     // No event sourcing
});

// Database-centric setup
services.AddMarventaFramework(options =>
{
    options.EnableBackgroundJobs = false;  // No job scheduling
    options.EnableDatabaseSeeding = true;  // Database initialization
    options.EnableProjections = true;      // Read model projections
});

Configuration:

// Background job configuration
options.BackgroundJobOptions.Provider = BackgroundJobProvider.Hangfire;
options.BackgroundJobOptions.ConnectionString = "Server=localhost;Database=Jobs";

Usage Examples:

// Schedule Background Job
var jobId = await _backgroundJobService.EnqueueAsync<IEmailService>(
    service => service.SendEmailAsync(emailMessage));

// Schedule Delayed Job
var delayedJobId = await _backgroundJobService.ScheduleAsync<IReportService>(
    service => service.GenerateMonthlyReportAsync(),
    TimeSpan.FromHours(24));

// Recurring Job
await _backgroundJobService.AddRecurringJobAsync(
    "daily-cleanup",
    () => _cleanupService.CleanupOldFilesAsync(),
    "0 2 * * *"); // Every day at 2 AM

// Job Status
var jobStatus = await _backgroundJobService.GetJobStatusAsync(jobId);
Console.WriteLine($"Job Status: {jobStatus.State}");

🛒 E-Commerce Features

Payment processing, shipping, and fraud detection

Enable/Disable Options:

// Full e-commerce platform
services.AddMarventaFramework(options =>
{
    options.EnableECommerce = true;        // E-Commerce Features
    options.EnablePayments = true;         // Payment Processing
    options.EnableShipping = true;         // Shipping Management
    options.EnableFraudDetection = true;   // Fraud Detection
});

// Payment-only setup
services.AddMarventaFramework(options =>
{
    options.EnableECommerce = false;       // No general e-commerce
    options.EnablePayments = true;         // Payment processing only
    options.EnableShipping = false;        // No shipping
    options.EnableFraudDetection = false;  // No fraud detection
});

// Non-e-commerce application
services.AddMarventaFramework(options =>
{
    options.EnableECommerce = false;       // No e-commerce features
    options.EnablePayments = false;        // No payment processing
    options.EnableShipping = false;        // No shipping
    options.EnableFraudDetection = false;  // No fraud detection
});

Usage Examples:

// Payment Processing
var payment = new Payment
{
    Amount = 99.99m,
    Currency = "USD",
    PaymentMethod = PaymentMethod.CreditCard,
    CustomerId = "cust-123"
};
var paymentResult = await _paymentService.ProcessPaymentAsync(payment);

// Shipping Management
var shipment = new Shipment
{
    OrderId = "order-123",
    ShippingAddress = shippingAddress,
    Carrier = ShippingCarrier.FedEx,
    TrackingNumber = "1234567890"
};
await _shippingService.CreateShipmentAsync(shipment);

// Track Shipment
var trackingInfo = await _shippingService.TrackShipmentAsync("1234567890");
Console.WriteLine($"Status: {trackingInfo.Status}, Location: {trackingInfo.CurrentLocation}");

// Fraud Detection
var fraudCheck = await _fraudService.CheckTransactionAsync(new FraudCheckRequest
{
    TransactionAmount = 99.99m,
    CustomerIP = "192.168.1.1",
    CustomerEmail = "customer@example.com",
    BillingAddress = billingAddress
});

if (fraudCheck.RiskScore > 0.7)
{
    // Flag as potentially fraudulent
    await _fraudService.FlagTransactionAsync(transactionId, FraudReason.HighRiskScore);
}

🌐 API Management

Versioning, idempotency, and HTTP client abstraction

Enable/Disable Options:

// Full API management suite
services.AddMarventaFramework(options =>
{
    options.EnableVersioning = true;       // API Versioning
    options.EnableHttpClient = true;       // HTTP Client Service
    options.EnableExceptionHandling = true; // Exception Handling
    options.EnableValidation = true;       // Validation Middleware
});

// Basic API setup
services.AddMarventaFramework(options =>
{
    options.EnableVersioning = false;      // Single version API
    options.EnableHttpClient = true;       // Keep HTTP client
    options.EnableExceptionHandling = true; // Keep error handling
    options.EnableValidation = true;       // Keep validation
});

// Minimal API setup
services.AddMarventaFramework(options =>
{
    options.EnableVersioning = false;      // No versioning
    options.EnableHttpClient = false;      // No external HTTP calls
    options.EnableExceptionHandling = false; // Use default handling
    options.EnableValidation = false;      // Use basic validation
});

Usage Examples:

// API Versioning
[ApiVersion("1.0")]
[ApiVersion("2.0")]
public class UsersController : VersionedControllerBase
{
    [HttpGet]
    [MapToApiVersion("1.0")]
    public async Task<IActionResult> GetUsersV1() { /* v1 logic */ }

    [HttpGet]
    [MapToApiVersion("2.0")]
    public async Task<IActionResult> GetUsersV2() { /* v2 logic */ }
}

// Idempotency
[HttpPost]
[Idempotent]
public async Task<IActionResult> CreateOrder([FromBody] CreateOrderRequest request)
{
    // This endpoint is automatically idempotent
    var order = await _orderService.CreateOrderAsync(request);
    return Ok(order);
}

// HTTP Client Service
var response = await _httpClientService.GetAsync<UserDto>("https://api.example.com/users/123");
var postResponse = await _httpClientService.PostAsync<CreateUserResponse, CreateUserRequest>(
    "https://api.example.com/users", createUserRequest);

⚙️ Configuration & Features

Feature flags and dynamic configuration

Enable/Disable Options:

// Enable advanced configuration features
services.AddMarventaFramework(options =>
{
    options.EnableFeatureFlags = true;    // Feature Flags
});

// Simple configuration (no feature flags)
services.AddMarventaFramework(options =>
{
    options.EnableFeatureFlags = false;   // No feature flags
});

Usage Examples:

// Feature Flags
var isNewCheckoutEnabled = await _featureFlagService.IsEnabledAsync("new-checkout-flow");
if (isNewCheckoutEnabled)
{
    // Use new checkout process
    return await ProcessNewCheckoutAsync(request);
}
else
{
    // Use legacy checkout
    return await ProcessLegacyCheckoutAsync(request);
}

// User-Specific Feature Flags
var hasAdvancedFeatures = await _featureFlagService.IsEnabledForUserAsync(
    "advanced-analytics", userId);

// Dynamic Configuration
var maxRetries = await _configurationService.GetValueAsync<int>("api.max-retries");
var timeout = await _configurationService.GetValueAsync<TimeSpan>("api.timeout");

// Configuration with Default
var cacheTimeout = await _configurationService.GetValueAsync("cache.timeout", TimeSpan.FromMinutes(30));

🔐 JWT Token Management

Advanced JWT token generation and management

Usage Examples:

// JWT Service Configuration
services.Configure<JwtOptions>(options =>
{
    options.SecretKey = "your-256-bit-secret-key";
    options.Issuer = "your-app";
    options.Audience = "your-audience";
    options.ExpirationMinutes = 60;
    options.RefreshTokenExpirationDays = 7;
});

// Generate Access and Refresh Tokens
var tokenResult = await _tokenService.GenerateTokenAsync(userId, new[]
{
    "admin", "user", "read:users", "write:orders"
});

Console.WriteLine($"Access Token: {tokenResult.AccessToken}");
Console.WriteLine($"Refresh Token: {tokenResult.RefreshToken}");
Console.WriteLine($"Expires At: {tokenResult.ExpiresAt}");

// Refresh Token
var refreshResult = await _tokenService.RefreshTokenAsync(refreshToken);
if (refreshResult.Success)
{
    // Use new tokens
    var newAccessToken = refreshResult.AccessToken;
    var newRefreshToken = refreshResult.RefreshToken;
}

// Validate Token
var validationResult = await _tokenService.ValidateTokenAsync(accessToken);
if (validationResult.IsValid)
{
    var userId = validationResult.UserId;
    var roles = validationResult.Roles;
    var claims = validationResult.Claims;
}

// Revoke Token
await _tokenService.RevokeTokenAsync(refreshToken);

🔑 API Key Authentication

Secure API key-based authentication middleware

Usage Examples:

// API Key Configuration
services.Configure<ApiKeyOptions>(options =>
{
    options.HeaderName = "X-API-Key";
    options.ValidApiKeys = new[]
    {
        new ApiKeyInfo { Key = "api-key-123", Name = "Mobile App", Permissions = new[] { "read", "write" } },
        new ApiKeyInfo { Key = "api-key-456", Name = "Web App", Permissions = new[] { "read" } }
    };
});

// Controller with API Key Protection
[ApiKey]
public class SecureApiController : ControllerBase
{
    [HttpGet("data")]
    public async Task<IActionResult> GetSecureData()
    {
        // Only accessible with valid API key
        return Ok(await _dataService.GetSecureDataAsync());
    }
}

// API Key with Specific Permissions
[ApiKey(RequiredPermissions = new[] { "admin", "write:orders" })]
public class AdminController : ControllerBase { }

// Get Current API Key Info
var apiKeyInfo = _currentUserService.GetCurrentApiKey();
Console.WriteLine($"API Key: {apiKeyInfo.Name}");
Console.WriteLine($"Permissions: {string.Join(", ", apiKeyInfo.Permissions)}");

🔒 Encryption Services

Data encryption, hashing, and security utilities

Usage Examples:

// Symmetric Encryption
var plainText = "sensitive customer data";
var encryptedData = await _encryptionService.EncryptAsync(plainText);
var decryptedData = await _encryptionService.DecryptAsync(encryptedData);

// Password Hashing with Salt
var password = "user-password";
var salt = await _encryptionService.GenerateSaltAsync();
var passwordHash = await _encryptionService.GenerateHashAsync(password, salt);

// Store salt and hash in database
await _userRepository.UpdatePasswordAsync(userId, passwordHash, salt);

// Verify Password
var storedHash = await _userRepository.GetPasswordHashAsync(userId);
var storedSalt = await _userRepository.GetPasswordSaltAsync(userId);
var isValidPassword = await _encryptionService.VerifyHashAsync(
    inputPassword, storedHash, storedSalt);

// Generate Secure Random Values
var randomKey = await _encryptionService.GenerateRandomKeyAsync(32); // 32 bytes
var randomId = await _encryptionService.GenerateRandomIdAsync(); // GUID-like string

// File Encryption
using var fileStream = File.OpenRead("document.pdf");
using var encryptedStream = await _encryptionService.EncryptStreamAsync(fileStream);
await _storageService.UploadFileAsync(encryptedStream, "encrypted-document.pdf");

🎭 Saga Pattern Management

Long-running business process orchestration

Usage Examples:

// Define a Saga
public class OrderProcessingSaga : ISaga<OrderProcessingState>
{
    public async Task<SagaResult> HandleAsync(OrderCreatedEvent @event, OrderProcessingState state)
    {
        // Step 1: Reserve Inventory
        var reserveResult = await _inventoryService.ReserveItemsAsync(@event.OrderId, @event.Items);
        if (!reserveResult.Success)
        {
            return SagaResult.Failed("Inventory reservation failed");
        }

        state.InventoryReserved = true;
        state.ReservationId = reserveResult.ReservationId;

        // Step 2: Process Payment
        var paymentResult = await _paymentService.ProcessPaymentAsync(@event.PaymentInfo);
        if (!paymentResult.Success)
        {
            // Compensate: Release inventory
            await _inventoryService.ReleaseReservationAsync(state.ReservationId);
            return SagaResult.Failed("Payment processing failed");
        }

        state.PaymentProcessed = true;
        state.PaymentId = paymentResult.PaymentId;

        return SagaResult.Completed();
    }
}

// Saga Manager Usage
var sagaId = await _sagaManager.StartSagaAsync<OrderProcessingSaga>(
    new OrderCreatedEvent { OrderId = orderId, Items = items, PaymentInfo = paymentInfo });

// Monitor Saga Status
var sagaStatus = await _sagaManager.GetSagaStatusAsync(sagaId);
Console.WriteLine($"Saga Status: {sagaStatus.State}");

// Handle Saga Compensation
if (sagaStatus.State == SagaState.Failed)
{
    await _sagaManager.CompensateSagaAsync(sagaId);
}

🗃️ Repository Pattern & Unit of Work

Generic repository with Unit of Work implementation

Usage Examples:

// Generic Repository Usage
public class UserService
{
    private readonly IRepository<User> _userRepository;
    private readonly IUnitOfWork _unitOfWork;

    public async Task<User> CreateUserAsync(CreateUserRequest request)
    {
        var user = new User(request.Email, request.FirstName, request.LastName);

        // Add to repository
        await _userRepository.AddAsync(user);

        // Save changes with Unit of Work
        await _unitOfWork.SaveChangesAsync();

        return user;
    }

    public async Task<User?> GetUserByEmailAsync(string email)
    {
        return await _userRepository.FirstOrDefaultAsync(u => u.Email == email);
    }

    public async Task<PagedResult<User>> GetUsersAsync(int page, int pageSize)
    {
        return await _userRepository.GetPagedAsync(
            pageNumber: page,
            pageSize: pageSize,
            orderBy: u => u.LastName);
    }
}

// Complex Repository Operations
var activeUsers = await _userRepository.FindAsync(
    predicate: u => u.IsActive && u.LastLoginDate > DateTime.UtcNow.AddDays(-30),
    orderBy: u => u.LastLoginDate,
    include: u => u.Profile);

// Bulk Operations
var users = await _userRepository.GetAllAsync();
foreach (var user in users.Where(u => u.ShouldUpdateStatus()))
{
    user.UpdateStatus();
}
await _unitOfWork.SaveChangesAsync();

// Transaction Management
using var transaction = await _unitOfWork.BeginTransactionAsync();
try
{
    await _userRepository.AddAsync(user);
    await _orderRepository.AddAsync(order);
    await _unitOfWork.SaveChangesAsync();
    await transaction.CommitAsync();
}
catch
{
    await transaction.RollbackAsync();
    throw;
}

💾 Caching Services

Distributed and in-memory caching with advanced features

Usage Examples:

// Basic Caching Operations
await _cacheService.SetAsync("user:123", userData, TimeSpan.FromHours(1));
var cachedUser = await _cacheService.GetAsync<UserData>("user:123");

// Cache with Tags (for bulk invalidation)
await _cacheService.SetAsync("product:456", productData, TimeSpan.FromMinutes(30),
    tags: new[] { "products", "category:electronics" });

// Invalidate by Tags
await _cacheService.InvalidateByTagAsync("products"); // Clears all product cache

// Cache-Aside Pattern
public async Task<User> GetUserAsync(int userId)
{
    var cacheKey = $"user:{userId}";
    var cachedUser = await _cacheService.GetAsync<User>(cacheKey);

    if (cachedUser == null)
    {
        cachedUser = await _userRepository.GetByIdAsync(userId);
        if (cachedUser != null)
        {
            await _cacheService.SetAsync(cacheKey, cachedUser, TimeSpan.FromMinutes(15));
        }
    }

    return cachedUser;
}

// Distributed Cache with Redis
services.Configure<CacheOptions>(options =>
{
    options.Provider = CacheProvider.Redis;
    options.ConnectionString = "localhost:6379";
    options.DefaultExpiration = TimeSpan.FromMinutes(30);
    options.KeyPrefix = "myapp:";
});

// Cache Statistics
var stats = await _cacheService.GetStatisticsAsync();
Console.WriteLine($"Hit Ratio: {stats.HitRatio:P2}");
Console.WriteLine($"Total Keys: {stats.TotalKeys}");

🚦 Rate Limiting

Advanced rate limiting with tenant-based controls

Usage Examples:

// Controller Rate Limiting
[RateLimit(RequestsPerMinute = 60)]
public class ApiController : ControllerBase
{
    [HttpGet("data")]
    [RateLimit(RequestsPerMinute = 10)] // Override for specific endpoint
    public async Task<IActionResult> GetData() => Ok();
}

// Tenant-Specific Rate Limiting
var isAllowed = await _tenantRateLimiter.TryAcquireAsync(
    tenantId: "tenant-123",
    endpoint: "api/orders",
    limit: 100,
    window: TimeSpan.FromMinutes(1));

if (!isAllowed)
{
    return StatusCode(429, "Rate limit exceeded for tenant");
}

// Custom Rate Limiting Logic
public class CustomRateLimitService
{
    public async Task<bool> CanUserPerformActionAsync(int userId, string action)
    {
        var key = $"user:{userId}:action:{action}";
        var count = await _cacheService.GetAsync<int>(key);

        if (count >= GetLimitForAction(action))
        {
            return false;
        }

        await _cacheService.SetAsync(key, count + 1, TimeSpan.FromHours(1));
        return true;
    }
}

// Rate Limit Configuration
services.Configure<RateLimitOptions>(options =>
{
    options.GlobalRules = new[]
    {
        new RateLimitRule { Endpoint = "/api/*", RequestsPerMinute = 1000 },
        new RateLimitRule { Endpoint = "/api/auth/*", RequestsPerMinute = 10 }
    };
    options.TenantSpecificLimits = true;
    options.BypassRoles = new[] { "admin", "system" };
});

🔒 Distributed Locking

Distributed locks for critical sections

Usage Examples:

// Basic Distributed Lock
using var lockHandle = await _distributedLock.AcquireAsync(
    resource: "invoice-generation",
    expiration: TimeSpan.FromMinutes(5));

if (lockHandle.IsAcquired)
{
    // Critical section - only one process can execute this
    await GenerateInvoiceAsync(orderId);
}
else
{
    // Lock acquisition failed
    throw new InvalidOperationException("Invoice generation already in progress");
}

// Try Lock with Timeout
using var lockHandle = await _distributedLock.TryAcquireAsync(
    resource: "user-profile-update:" + userId,
    expiration: TimeSpan.FromMinutes(2),
    timeout: TimeSpan.FromSeconds(30));

if (lockHandle.IsAcquired)
{
    // Update user profile
    await UpdateUserProfileAsync(userId, profileData);
}

// Lock with Custom Options
var lockOptions = new DistributedLockOptions
{
    Resource = "payment-processing:" + paymentId,
    Expiration = TimeSpan.FromMinutes(10),
    RetryDelay = TimeSpan.FromSeconds(1),
    MaxRetries = 5
};

using var lockHandle = await _distributedLock.AcquireAsync(lockOptions);

// Extend Lock Duration
if (lockHandle.IsAcquired)
{
    // Start long operation
    await longRunningOperation();

    // Extend lock if needed
    await lockHandle.ExtendAsync(TimeSpan.FromMinutes(5));

    // Continue operation
    await continueOperation();
}

⚡ Idempotency Support

Ensure operations can be safely retried

Usage Examples:

// Controller with Idempotency
[HttpPost("orders")]
[Idempotent]
public async Task<IActionResult> CreateOrder([FromBody] CreateOrderRequest request)
{
    // This endpoint is automatically idempotent based on request content
    var order = await _orderService.CreateOrderAsync(request);
    return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order);
}

// Custom Idempotency Key
[HttpPost("payments")]
[Idempotent(KeyHeader = "Idempotency-Key")]
public async Task<IActionResult> ProcessPayment([FromBody] PaymentRequest request)
{
    // Uses custom header for idempotency key
    var payment = await _paymentService.ProcessPaymentAsync(request);
    return Ok(payment);
}

// Service-Level Idempotency
public class OrderService
{
    public async Task<Order> CreateOrderAsync(CreateOrderRequest request)
    {
        var idempotencyKey = GenerateIdempotencyKey(request);

        return await _idempotencyService.ExecuteAsync(
            key: idempotencyKey,
            operation: async () =>
            {
                var order = new Order(request.CustomerId, request.Items);
                await _orderRepository.AddAsync(order);
                await _unitOfWork.SaveChangesAsync();
                return order;
            },
            expiration: TimeSpan.FromHours(24));
    }
}

// Manual Idempotency Check
var operationResult = await _idempotencyService.GetResultAsync<PaymentResult>(idempotencyKey);
if (operationResult.HasResult)
{
    // Operation already completed
    return operationResult.Result;
}

// Execute and store result
var result = await ProcessPaymentInternalAsync(request);
await _idempotencyService.StoreResultAsync(idempotencyKey, result, TimeSpan.FromDays(7));
return result;

🏥 Health Checks

Comprehensive system health monitoring

Usage Examples:

// Health Check Registration
services.AddHealthChecks()
    .AddMarventaHealthChecks() // Framework health checks
    .AddDbContextCheck<ApplicationDbContext>()
    .AddRedisCheck("localhost:6379")
    .AddElasticsearchCheck("http://localhost:9200");

// Custom Health Check
public class CustomHealthCheck : IHealthCheck
{
    public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context)
    {
        try
        {
            // Check external service
            var response = await _httpClient.GetAsync("https://api.external-service.com/health");

            if (response.IsSuccessStatusCode)
            {
                return HealthCheckResult.Healthy("External service is responsive");
            }

            return HealthCheckResult.Degraded("External service is slow");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy("External service is down", ex);
        }
    }
}

// Health Check Controller
[ApiController]
[Route("health")]
public class HealthController : ControllerBase
{
    private readonly IHealthCheck _healthCheck;

    [HttpGet]
    public async Task<IActionResult> GetHealth()
    {
        var health = await _healthCheck.CheckHealthAsync();

        var response = new
        {
            Status = health.Status.ToString(),
            Checks = health.Checks.Select(c => new
            {
                Name = c.Key,
                Status = c.Value.Status.ToString(),
                Description = c.Value.Description,
                Duration = c.Value.Duration
            }),
            TotalDuration = health.TotalDuration
        };

        var statusCode = health.Status == HealthStatus.Healthy ? 200 : 503;
        return StatusCode(statusCode, response);
    }
}

// Detailed Health Information
var healthResult = await _healthCheck.CheckHealthAsync();
foreach (var check in healthResult.Checks)
{
    Console.WriteLine($"{check.Key}: {check.Value.Status}");
    if (check.Value.Exception != null)
    {
        Console.WriteLine($"  Error: {check.Value.Exception.Message}");
    }
}

🔍 Observability & Correlation

Distributed tracing and correlation tracking

Usage Examples:

// Correlation Context Usage
public class OrderController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CreateOrder([FromBody] CreateOrderRequest request)
    {
        // Correlation ID is automatically generated and propagated
        var correlationId = _correlationContext.CorrelationId;

        _logger.LogInformation("Processing order creation with correlation ID: {CorrelationId}", correlationId);

        // Call other services (correlation ID is automatically passed)
        await _inventoryService.ReserveItemsAsync(request.Items);
        await _paymentService.ProcessPaymentAsync(request.Payment);

        return Ok();
    }
}

// Custom Activity Tracking
using var activity = _activityService.StartActivity("order-processing");
activity.SetTag("order.id", orderId);
activity.SetTag("customer.id", customerId);

try
{
    await ProcessOrderAsync(orderId);
    activity.SetStatus(ActivityStatusCode.Ok);
}
catch (Exception ex)
{
    activity.SetStatus(ActivityStatusCode.Error, ex.Message);
    throw;
}

// Distributed Tracing Configuration
services.Configure<ObservabilityOptions>(options =>
{
    options.ServiceName = "order-service";
    options.ServiceVersion = "1.0.0";
    options.JaegerEndpoint = "http://localhost:14268/api/traces";
    options.SamplingRatio = 0.1; // Sample 10% of traces
});

// Manual Correlation ID
_correlationContext.SetCorrelationId("custom-correlation-id");
var currentId = _correlationContext.CorrelationId;

// Correlation Middleware automatically adds correlation ID to:
// - HTTP response headers
// - Log entries
// - Outgoing HTTP requests
// - Message bus events

📝 Logging Service

Structured logging with correlation and context

Usage Examples:

// Basic Logging
_loggerService.LogInformation("User {UserId} logged in", userId);
_loggerService.LogWarning("Rate limit exceeded for user {UserId}", userId);
_loggerService.LogError(exception, "Failed to process order {OrderId}", orderId);

// Structured Logging with Context
_loggerService.LogInformation("Order processed successfully", new
{
    OrderId = orderId,
    CustomerId = customerId,
    Amount = order.TotalAmount,
    ProcessingTime = stopwatch.ElapsedMilliseconds,
    CorrelationId = _correlationContext.CorrelationId
});

// Performance Logging
using var performanceLogger = _loggerService.BeginScope("order-processing");
performanceLogger.LogInformation("Starting order processing");

var stopwatch = Stopwatch.StartNew();
await ProcessOrderAsync(orderId);
stopwatch.Stop();

performanceLogger.LogInformation("Order processing completed in {Duration}ms", stopwatch.ElapsedMilliseconds);

// Custom Log Categories
var categoryLogger = _loggerService.CreateLogger("PaymentProcessing");
categoryLogger.LogInformation("Payment gateway response: {Response}", response);

// Log Configuration with Serilog
services.Configure<LoggingOptions>(options =>
{
    options.MinimumLevel = LogLevel.Information;
    options.EnrichWithCorrelationId = true;
    options.EnrichWithUserContext = true;
    options.Sinks = new[]
    {
        new LogSinkConfiguration { Type = "Console" },
        new LogSinkConfiguration { Type = "File", Path = "logs/app-.txt" },
        new LogSinkConfiguration { Type = "Elasticsearch", ConnectionString = "http://localhost:9200" }
    };
});

📧 Email Service

Advanced email sending with templates and attachments

Usage Examples:

// Basic Email
await _emailService.SendEmailAsync(new EmailMessage
{
    To = "customer@example.com",
    Subject = "Order Confirmation",
    HtmlBody = "<h1>Thank you for your order!</h1><p>Order #12345</p>",
    PlainTextBody = "Thank you for your order! Order #12345"
});

// Email with Attachments
var attachments = new[]
{
    new EmailAttachment
    {
        FileName = "invoice.pdf",
        Content = invoicePdfBytes,
        ContentType = "application/pdf"
    },
    new EmailAttachment
    {
        FileName = "receipt.jpg",
        Content = receiptImageBytes,
        ContentType = "image/jpeg"
    }
};

await _emailService.SendEmailAsync(new EmailMessage
{
    To = "customer@example.com",
    Subject = "Your Invoice",
    HtmlBody = emailTemplate,
    Attachments = attachments
});

// Bulk Email
var recipients = new[] { "user1@example.com", "user2@example.com", "user3@example.com" };
var bulkResult = await _emailService.SendBulkEmailAsync(
    recipients: recipients,
    subject: "Monthly Newsletter",
    htmlBody: newsletterTemplate);

Console.WriteLine($"Sent: {bulkResult.SuccessfulSends}, Failed: {bulkResult.FailedSends}");

// Email Templates
var templateData = new
{
    CustomerName = "John Doe",
    OrderId = "12345",
    Items = order.Items,
    TotalAmount = order.TotalAmount
};

await _emailService.SendTemplatedEmailAsync(
    to: "customer@example.com",
    templateId: "order-confirmation",
    templateData: templateData);

// Email Service Configuration
services.Configure<EmailOptions>(options =>
{
    options.Provider = EmailProvider.SendGrid;
    options.ApiKey = "your-sendgrid-api-key";
    options.FromEmail = "noreply@yourcompany.com";
    options.FromName = "Your Company";
    options.EnableTracking = true;
    options.DefaultTimeout = TimeSpan.FromSeconds(30);
});

📱 SMS Service

SMS sending with multiple providers and bulk support

Usage Examples:

// Basic SMS
await _smsService.SendSmsAsync(
    phoneNumber: "+1234567890",
    message: "Your verification code is: 123456");

// SMS with Options
var smsResult = await _smsService.SendSmsAsync(new SmsMessage
{
    PhoneNumber = "+1234567890",
    Message = "Welcome to our service!",
    SendAt = DateTime.UtcNow.AddMinutes(5), // Scheduled SMS
    ValidityPeriod = TimeSpan.FromHours(1)
});

if (smsResult.Success)
{
    Console.WriteLine($"SMS sent with ID: {smsResult.MessageId}");
}

// Bulk SMS
var phoneNumbers = new[] { "+1234567890", "+1987654321", "+1555123456" };
var bulkResult = await _smsService.SendBulkSmsAsync(
    phoneNumbers: phoneNumbers,
    message: "Don't miss our flash sale! 50% off everything today only.");

Console.WriteLine($"Sent: {bulkResult.SuccessfulSends}, Failed: {bulkResult.FailedSends}");

// SMS Templates
await _smsService.SendTemplatedSmsAsync(
    phoneNumber: "+1234567890",
    templateId: "order-shipped",
    templateData: new { CustomerName = "John", TrackingNumber = "1Z999AA1234567890" });

// SMS Status Check
var status = await _smsService.GetMessageStatusAsync(messageId);
Console.WriteLine($"Message Status: {status.Status}"); // Sent, Delivered, Failed

// SMS Configuration
services.Configure<SmsOptions>(options =>
{
    options.Provider = SmsProvider.Twilio;
    options.AccountSid = "your-twilio-account-sid";
    options.AuthToken = "your-twilio-auth-token";
    options.FromPhoneNumber = "+1234567890";
    options.DefaultTimeout = TimeSpan.FromSeconds(30);
});

🚌 Message Bus

Reliable message publishing and handling

Usage Examples:

// Publish Message
await _messageBus.PublishAsync(new OrderCreatedMessage
{
    OrderId = orderId,
    CustomerId = customerId,
    Items = order.Items,
    TotalAmount = order.TotalAmount,
    CreatedAt = DateTime.UtcNow
});

// Message Handler
public class OrderCreatedMessageHandler : IMessageHandler<OrderCreatedMessage>
{
    public async Task HandleAsync(OrderCreatedMessage message)
    {
        // Send confirmation email
        await _emailService.SendOrderConfirmationAsync(message.CustomerId, message.OrderId);

        // Update inventory
        await _inventoryService.ReserveItemsAsync(message.Items);

        // Log analytics event
        await _analyticsService.TrackEventAsync("order_created", new
        {
            OrderId = message.OrderId,
            Amount = message.TotalAmount
        });
    }
}

// Request-Response Pattern
var response = await _messageBus.RequestAsync<GetUserQuery, UserDto>(
    new GetUserQuery { UserId = 123 });

// Delayed Message
await _messageBus.ScheduleAsync(
    message: new SendReminderMessage { UserId = userId, Type = "payment" },
    delay: TimeSpan.FromDays(3));

// Message Bus Configuration
services.Configure<MessageBusOptions>(options =>
{
    options.Provider = MessageBusProvider.RabbitMQ;
    options.ConnectionString = "amqp://localhost";
    options.ExchangeName = "marventa.events";
    options.RetryAttempts = 3;
    options.RetryDelay = TimeSpan.FromSeconds(5);
    options.EnableDeadLetterQueue = true;
});

// Batch Message Publishing
var messages = new IMessage[]
{
    new UserRegisteredMessage { UserId = 1, Email = "user1@example.com" },
    new UserRegisteredMessage { UserId = 2, Email = "user2@example.com" },
    new UserRegisteredMessage { UserId = 3, Email = "user3@example.com" }
};

await _messageBus.PublishBatchAsync(messages);

🗂️ Database Seeding

Automated database initialization and test data

Usage Examples:

// Basic Database Seeding
public class UserSeeder : IDatabaseSeeder
{
    public async Task SeedAsync()
    {
        if (!await _context.Users.AnyAsync())
        {
            var users = new[]
            {
                new User("admin@example.com", "Admin", "User") { Role = "Administrator" },
                new User("user@example.com", "Regular", "User") { Role = "User" }
            };

            await _context.Users.AddRangeAsync(users);
            await _context.SaveChangesAsync();
        }
    }
}

// Conditional Seeding
public class ProductSeeder : IDatabaseSeeder
{
    public async Task SeedAsync()
    {
        // Only seed in development environment
        if (_environment.IsDevelopment())
        {
            await SeedTestProductsAsync();
        }

        // Always ensure categories exist
        await EnsureCategoriesExistAsync();
    }
}

// Ordered Seeding
[SeederOrder(1)]
public class CategorySeeder : IDatabaseSeeder { }

[SeederOrder(2)]
public class ProductSeeder : IDatabaseSeeder { } // Runs after categories

// Seeding Configuration
services.Configure<DatabaseSeedingOptions>(options =>
{
    options.EnableSeeding = true;
    options.SeedInProduction = false;
    options.SeedDataPath = "Data/SeedData";
});

// Run Seeders
public class Program
{
    public static async Task Main(string[] args)
    {
        var app = builder.Build();

        // Run database seeders
        using var scope = app.Services.CreateScope();
        var seederManager = scope.ServiceProvider.GetRequiredService<IDatabaseSeederManager>();
        await seederManager.SeedAllAsync();

        app.Run();
    }
}

// File-Based Seeding
public class JsonFileSeeder : IDatabaseSeeder
{
    public async Task SeedAsync()
    {
        var seedDataPath = Path.Combine("Data", "products.json");
        if (File.Exists(seedDataPath))
        {
            var json = await File.ReadAllTextAsync(seedDataPath);
            var products = JsonSerializer.Deserialize<Product[]>(json);

            foreach (var product in products)
            {
                if (!await _context.Products.AnyAsync(p => p.Sku == product.Sku))
                {
                    await _context.Products.AddAsync(product);
                }
            }

            await _context.SaveChangesAsync();
        }
    }
}

📊 Projections (Event Sourcing)

Event sourcing projections and read models

Usage Examples:

// Event Sourcing Projection
public class UserStatisticsProjection : IProjection
{
    public async Task ProjectAsync(IDomainEvent domainEvent)
    {
        switch (domainEvent)
        {
            case UserRegisteredEvent userRegistered:
                await HandleUserRegisteredAsync(userRegistered);
                break;

            case UserLoginEvent userLogin:
                await HandleUserLoginAsync(userLogin);
                break;

            case OrderCreatedEvent orderCreated:
                await HandleOrderCreatedAsync(orderCreated);
                break;
        }
    }

    private async Task HandleUserRegisteredAsync(UserRegisteredEvent @event)
    {
        var stats = new UserStatistics
        {
            UserId = @event.UserId,
            RegistrationDate = @event.RegistrationDate,
            TotalOrders = 0,
            TotalSpent = 0,
            LastLoginDate = null
        };

        await _statisticsRepository.AddAsync(stats);
    }
}

// Real-time Projection Updates
public class OrderProjection : IProjection
{
    public async Task ProjectAsync(IDomainEvent domainEvent)
    {
        if (domainEvent is OrderCreatedEvent orderCreated)
        {
            // Update user statistics
            var userStats = await _statisticsRepository.GetByUserIdAsync(orderCreated.CustomerId);
            userStats.TotalOrders++;
            userStats.TotalSpent += orderCreated.TotalAmount;
            userStats.LastOrderDate = orderCreated.CreatedAt;

            await _statisticsRepository.UpdateAsync(userStats);

            // Update monthly sales projection
            var monthlySales = await _monthlySalesRepository.GetCurrentMonthAsync();
            monthlySales.TotalSales += orderCreated.TotalAmount;
            monthlySales.OrderCount++;

            await _monthlySalesRepository.UpdateAsync(monthlySales);
        }
    }
}

// Projection Manager
public class ProjectionManager
{
    public async Task RebuildProjectionAsync<T>() where T : IProjection
    {
        // Get all events from event store
        var events = await _eventStore.GetAllEventsAsync();

        // Clear existing projection data
        await _projectionRepository.ClearAsync<T>();

        // Replay all events
        var projection = _serviceProvider.GetRequiredService<T>();
        foreach (var @event in events.OrderBy(e => e.Timestamp))
        {
            await projection.ProjectAsync(@event);
        }
    }
}

// Query Read Models
public class UserDashboardQuery
{
    public async Task<UserDashboardDto> GetUserDashboardAsync(int userId)
    {
        var userStats = await _statisticsRepository.GetByUserIdAsync(userId);
        var recentOrders = await _orderProjectionRepository.GetRecentOrdersAsync(userId, 5);

        return new UserDashboardDto
        {
            TotalOrders = userStats.TotalOrders,
            TotalSpent = userStats.TotalSpent,
            LastLoginDate = userStats.LastLoginDate,
            RecentOrders = recentOrders
        };
    }
}

// Projection Configuration
services.Configure<ProjectionOptions>(options =>
{
    options.EnableRealTimeProjections = true;
    options.BatchSize = 1000;
    options.RetryAttempts = 3;
    options.SnapshotInterval = TimeSpan.FromHours(1);
});

💳 Payment Processing

Comprehensive payment processing with multiple gateways

Usage Examples:

// Basic Payment Processing
var paymentRequest = new PaymentRequest
{
    Amount = 99.99m,
    Currency = "USD",
    PaymentMethod = new CreditCardPaymentMethod
    {
        CardNumber = "4111111111111111",
        ExpiryMonth = 12,
        ExpiryYear = 2025,
        CVV = "123",
        CardholderName = "John Doe"
    },
    CustomerId = "cust_123",
    OrderId = "order_456"
};

var paymentResult = await _paymentService.ProcessPaymentAsync(paymentRequest);

if (paymentResult.Success)
{
    Console.WriteLine($"Payment successful! Transaction ID: {paymentResult.TransactionId}");
}
else
{
    Console.WriteLine($"Payment failed: {paymentResult.ErrorMessage}");
}

// Multiple Payment Methods
var digitalWalletPayment = new PaymentRequest
{
    Amount = 149.99m,
    Currency = "USD",
    PaymentMethod = new DigitalWalletPaymentMethod
    {
        WalletType = DigitalWalletType.PayPal,
        WalletToken = "paypal_token_123"
    }
};

var bankTransferPayment = new PaymentRequest
{
    Amount = 299.99m,
    Currency = "EUR",
    PaymentMethod = new BankTransferPaymentMethod
    {
        BankAccount = "DE89370400440532013000",
        BankCode = "COBADEFFXXX"
    }
};

// Recurring Payments
var subscriptionPayment = new RecurringPaymentRequest
{
    Amount = 29.99m,
    Currency = "USD",
    PaymentMethod = paymentMethod,
    RecurrencePattern = RecurrencePattern.Monthly,
    StartDate = DateTime.UtcNow,
    EndDate = DateTime.UtcNow.AddYears(1)
};

var recurringResult = await _paymentService.CreateRecurringPaymentAsync(subscriptionPayment);

// Payment Refunds
var refundResult = await _paymentService.RefundPaymentAsync(new RefundRequest
{
    TransactionId = "txn_123",
    Amount = 50.00m, // Partial refund
    Reason = "Customer requested partial refund"
});

// Payment Status Tracking
var paymentStatus = await _paymentService.GetPaymentStatusAsync("txn_123");
Console.WriteLine($"Payment Status: {paymentStatus.Status}");
Console.WriteLine($"Gateway Response: {paymentStatus.GatewayResponse}");

// Payment Gateway Configuration
services.Configure<PaymentOptions>(options =>
{
    options.DefaultGateway = PaymentGateway.Stripe;
    options.Gateways = new Dictionary<PaymentGateway, PaymentGatewayConfig>
    {
        [PaymentGateway.Stripe] = new()
        {
            ApiKey = "sk_test_...",
            WebhookSecret = "whsec_...",
            EnableTestMode = true
        },
        [PaymentGateway.PayPal] = new()
        {
            ClientId = "paypal_client_id",
            ClientSecret = "paypal_client_secret",
            Environment = "sandbox"
        }
    };
});

🚚 Shipping Management

Complete shipping and logistics management

Usage Examples:

// Create Shipment
var shipment = new CreateShipmentRequest
{
    OrderId = "order_123",
    ShippingAddress = new Address
    {
        Name = "John Doe",
        Street = "123 Main St",
        City = "New York",
        State = "NY",
        PostalCode = "10001",
        Country = "USA"
    },
    Items = order.Items,
    Carrier = ShippingCarrier.FedEx,
    ServiceType = ShippingServiceType.Standard,
    PackageType = PackageType.Box,
    Weight = 2.5m,
    Dimensions = new Dimensions { Length = 10, Width = 8, Height = 6 }
};

var shipmentResult = await _shippingService.CreateShipmentAsync(shipment);

if (shipmentResult.Success)
{
    Console.WriteLine($"Shipment created! Tracking: {shipmentResult.TrackingNumber}");
    Console.WriteLine($"Estimated delivery: {shipmentResult.EstimatedDeliveryDate}");
}

// Track Shipment
var trackingInfo = await _shippingService.TrackShipmentAsync("1Z999AA1234567890");
Console.WriteLine($"Status: {trackingInfo.Status}");
Console.WriteLine($"Current Location: {trackingInfo.CurrentLocation}");

foreach (var update in trackingInfo.TrackingHistory)
{
    Console.WriteLine($"{update.Timestamp}: {update.Status} - {update.Location}");
}

// Calculate Shipping Rates
var rateRequest = new ShippingRateRequest
{
    OriginAddress = warehouseAddress,
    DestinationAddress = customerAddress,
    Packages = new[]
    {
        new Package { Weight = 2.5m, Dimensions = new Dimensions { Length = 10, Width = 8, Height = 6 } }
    }
};

var rates = await _shippingService.GetShippingRatesAsync(rateRequest);

foreach (var rate in rates)
{
    Console.WriteLine($"{rate.Carrier} {rate.ServiceType}: ${rate.Cost} (Delivery: {rate.EstimatedDeliveryDate})");
}

// Bulk Shipping
var bulkShipments = orders.Select(order => new CreateShipmentRequest
{
    OrderId = order.Id,
    ShippingAddress = order.ShippingAddress,
    Items = order.Items,
    Carrier = ShippingCarrier.UPS
}).ToArray();

var bulkResult = await _shippingService.CreateBulkShipmentsAsync(bulkShipments);
Console.WriteLine($"Created {bulkResult.SuccessfulShipments} shipments, {bulkResult.FailedShipments} failed");

// Shipping Configuration
services.Configure<ShippingOptions>(options =>
{
    options.DefaultCarrier = ShippingCarrier.FedEx;
    options.Carriers = new Dictionary<ShippingCarrier, CarrierConfig>
    {
        [ShippingCarrier.FedEx] = new()
        {
            AccountNumber = "123456789",
            ApiKey = "fedex_api_key",
            ApiSecret = "fedex_api_secret",
            EnableTestMode = true
        },
        [ShippingCarrier.UPS] = new()
        {
            Username = "ups_username",
            Password = "ups_password",
            AccessKey = "ups_access_key"
        }
    };
});

🛡️ Fraud Detection

Advanced fraud detection and prevention

Usage Examples:

// Real-time Fraud Check
var fraudCheck = await _fraudService.CheckTransactionAsync(new FraudCheckRequest
{
    TransactionId = "txn_123",
    CustomerId = "cust_456",
    Amount = 299.99m,
    Currency = "USD",
    PaymentMethod = PaymentMethodType.CreditCard,
    CustomerIP = "192.168.1.1",
    UserAgent = "Mozilla/5.0...",
    BillingAddress = billingAddress,
    ShippingAddress = shippingAddress,
    DeviceFingerprint = "device_fp_123",
    SessionId = "session_456"
});

Console.WriteLine($"Risk Score: {fraudCheck.RiskScore:P2}");
Console.WriteLine($"Recommendation: {fraudCheck.Recommendation}");

if (fraudCheck.RiskScore > 0.7)
{
    // High risk - require manual review
    await _fraudService.FlagForReviewAsync(fraudCheck.TransactionId, FraudReason.HighRiskScore);

    // Notify fraud team
    await _notificationService.NotifyFraudTeamAsync(fraudCheck);
}
else if (fraudCheck.RiskScore > 0.3)
{
    // Medium risk - require additional verification
    await _fraudService.RequireAdditionalVerificationAsync(fraudCheck.TransactionId);
}

// Fraud Detection Rules
var customRules = new[]
{
    new FraudRule
    {
        Name = "High Velocity Transactions",
        Condition = "TransactionsInLast24Hours > 10",
        RiskWeight = 0.3
    },
    new FraudRule
    {
        Name = "Unusual Location",
        Condition = "CustomerLocationDifferentFromUsual",
        RiskWeight = 0.4
    },
    new FraudRule
    {
        Name = "Large Amount",
        Condition = "Amount > CustomerAverageTransaction * 5",
        RiskWeight = 0.5
    }
};

await _fraudService.UpdateRulesAsync(customRules);

// Velocity Checks
var velocityCheck = await _fraudService.CheckVelocityAsync(new VelocityCheckRequest
{
    CustomerId = "cust_123",
    CheckType = VelocityCheckType.TransactionCount,
    TimeWindow = TimeSpan.FromHours(24),
    Threshold = 10
});

if (velocityCheck.ExceedsThreshold)
{
    Console.WriteLine($"Customer exceeded velocity limit: {velocityCheck.CurrentCount}/{velocityCheck.Threshold}");
}

// Device Analysis
var deviceAnalysis = await _fraudService.AnalyzeDeviceAsync(new DeviceAnalysisRequest
{
    DeviceFingerprint = "device_fp_123",
    IPAddress = "192.168.1.1",
    UserAgent = "Mozilla/5.0..."
});

if (deviceAnalysis.IsKnownFraudDevice)
{
    await _fraudService.BlockTransactionAsync(transactionId, FraudReason.KnownFraudDevice);
}

// Machine Learning Fraud Detection
var mlPrediction = await _fraudService.GetMLPredictionAsync(new MLFraudRequest
{
    TransactionFeatures = new
    {
        Amount = 299.99,
        Hour = DateTime.Now.Hour,
        DayOfWeek = (int)DateTime.Now.DayOfWeek,
        CustomerAge = 35,
        CustomerAccountAge = 365,
        PreviousTransactionCount = 25,
        AverageTransactionAmount = 89.50
    }
});

Console.WriteLine($"ML Fraud Probability: {mlPrediction.FraudProbability:P2}");

🌐 API Versioning

Comprehensive API versioning strategies

Usage Examples:

// Controller Versioning
[ApiVersion("1.0")]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/users")]
public class UsersController : VersionedControllerBase
{
    [HttpGet]
    [MapToApiVersion("1.0")]
    public async Task<IActionResult> GetUsersV1()
    {
        var users = await _userService.GetUsersAsync();
        return Ok(users.Select(u => new UserV1Dto(u)));
    }

    [HttpGet]
    [MapToApiVersion("2.0")]
    public async Task<IActionResult> GetUsersV2()
    {
        var users = await _userService.GetUsersAsync();
        return Ok(users.Select(u => new UserV2Dto(u))); // Enhanced DTO with more fields
    }

    [HttpGet("{id}")]
    [MapToApiVersion("1.0")]
    [MapToApiVersion("2.0")]
    public async Task<IActionResult> GetUser(int id)
    {
        var user = await _userService.GetUserAsync(id);

        // Version-specific response
        return ApiVersion.ToString() switch
        {
            "1.0" => Ok(new UserV1Dto(user)),
            "2.0" => Ok(new UserV2Dto(user)),
            _ => BadRequest("Unsupported API version")
        };
    }
}

// Header-Based Versioning
[Route("api/products")]
public class ProductsController : VersionedControllerBase
{
    [HttpGet]
    [ApiVersion("1.0")]
    public async Task<IActionResult> GetProducts()
    {
        // Check version from header: X-API-Version: 1.0
        var version = GetRequestedApiVersion();
        var products = await _productService.GetProductsAsync();

        return version.MajorVersion switch
        {
            1 => Ok(products.Select(p => new ProductV1Dto(p))),
            2 => Ok(products.Select(p => new ProductV2Dto(p))),
            _ => BadRequest("Unsupported API version")
        };
    }
}

// Query Parameter Versioning
[Route("api/orders")]
public class OrdersController : VersionedControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetOrders([FromQuery] string version = "1.0")
    {
        var orders = await _orderService.GetOrdersAsync();

        return version switch
        {
            "1.0" => Ok(orders.Select(o => new OrderV1Dto(o))),
            "2.0" => Ok(orders.Select(o => new OrderV2Dto(o))),
            _ => BadRequest($"Unsupported version: {version}")
        };
    }
}

// Version-Specific Models
public class UserV1Dto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

public class UserV2Dto : UserV1Dto
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime CreatedAt { get; set; }
    public string ProfileImageUrl { get; set; }
}

// API Versioning Configuration
services.AddApiVersioning(options =>
{
    options.DefaultApiVersion = new ApiVersion(1, 0);
    options.AssumeDefaultVersionWhenUnspecified = true;
    options.ApiVersionReader = ApiVersionReader.Combine(
        new UrlSegmentApiVersionReader(),
        new HeaderApiVersionReader("X-API-Version"),
        new QueryStringApiVersionReader("version")
    );
});

// Version Discovery
[HttpGet("api/versions")]
public class VersionController : ControllerBase
{
    public IActionResult GetSupportedVersions()
    {
        return Ok(new
        {
            SupportedVersions = new[] { "1.0", "2.0", "3.0" },
            DefaultVersion = "2.0",
            DeprecatedVersions = new[] { "1.0" },
            SunsetDate = new { Version = "1.0", Date = "2024-12-31" }
        });
    }
}

🌐 HTTP Client Service

Simplified HTTP client with retry policies and circuit breakers

Usage Examples:

// Basic HTTP Requests
var user = await _httpClientService.GetAsync<UserDto>("https://api.example.com/users/123");
var posts = await _httpClientService.GetAsync<List<PostDto>>("https://api.example.com/posts");

// POST Request
var createUserRequest = new CreateUserRequest { Name = "John Doe", Email = "john@example.com" };
var createdUser = await _httpClientService.PostAsync<UserDto, CreateUserRequest>(
    "https://api.example.com/users", createUserRequest);

// PUT and DELETE
await _httpClientService.PutAsync("https://api.example.com/users/123", updateUserRequest);
await _httpClientService.DeleteAsync("https://api.example.com/users/123");

// Custom Headers
var headers = new Dictionary<string, string>
{
    ["Authorization"] = "Bearer token123",
    ["X-API-Key"] = "api_key_456",
    ["X-Correlation-ID"] = Guid.NewGuid().ToString()
};

var response = await _httpClientService.GetAsync<OrderDto>(
    "https://api.example.com/orders/789", headers);

// Retry Policies
var retryPolicy = new RetryPolicy
{
    MaxRetries = 3,
    DelayBetweenRetries = TimeSpan.FromSeconds(2),
    ExponentialBackoff = true,
    RetryOn = new[] { HttpStatusCode.ServiceUnavailable, HttpStatusCode.RequestTimeout }
};

var resilientResponse = await _httpClientService.GetWithRetryAsync<ProductDto>(
    "https://api.external.com/products/123", retryPolicy);

// Circuit Breaker
var circuitBreakerPolicy = new CircuitBreakerPolicy
{
    FailureThreshold = 5,
    BreakDuration = TimeSpan.FromMinutes(1),
    SuccessThreshold = 3
};

var protectedResponse = await _httpClientService.GetWithCircuitBreakerAsync<WeatherDto>(
    "https://api.weather.com/current", circuitBreakerPolicy);

// File Upload
using var fileStream = File.OpenRead("document.pdf");
var uploadResult = await _httpClientService.UploadFileAsync(
    "https://api.example.com/files/upload",
    fileStream,
    "document.pdf",
    "application/pdf");

// Download File
using var downloadStream = await _httpClientService.DownloadFileAsync(
    "https://api.example.com/files/download/123");

// Timeout Configuration
var timeoutResult = await _httpClientService.GetAsync<DataDto>(
    "https://slow-api.example.com/data",
    timeout: TimeSpan.FromSeconds(30));

// HTTP Client Configuration
services.Configure<HttpClientOptions>(options =>
{
    options.DefaultTimeout = TimeSpan.FromSeconds(30);
    options.MaxRetries = 3;
    options.EnableCircuitBreaker = true;
    options.BaseAddress = "https://api.myservice.com";
    options.DefaultHeaders = new Dictionary<string, string>
    {
        ["User-Agent"] = "MyApp/1.0",
        ["Accept"] = "application/json"
    };
});

⚠️ Exception Handling

Global exception handling with custom exceptions

Usage Examples:

// Custom Business Exceptions
public class InsufficientInventoryException : BusinessException
{
    public int ProductId { get; }
    public int RequestedQuantity { get; }
    public int AvailableQuantity { get; }

    public InsufficientInventoryException(int productId, int requested, int available)
        : base($"Insufficient inventory for product {productId}. Requested: {requested}, Available: {available}")
    {
        ProductId = productId;
        RequestedQuantity = requested;
        AvailableQuantity = available;
    }
}

// Service Layer Usage
public class OrderService
{
    public async Task<Order> CreateOrderAsync(CreateOrderRequest request)
    {
        foreach (var item in request.Items)
        {
            var product = await _productRepository.GetByIdAsync(item.ProductId);
            if (product == null)
            {
                throw new NotFoundException($"Product with ID {item.ProductId} not found");
            }

            if (product.InventoryCount < item.Quantity)
            {
                throw new InsufficientInventoryException(
                    item.ProductId, item.Quantity, product.InventoryCount);
            }
        }

        var order = new Order(request.CustomerId, request.Items);
        await _orderRepository.AddAsync(order);
        return order;
    }
}

// Controller with Exception Handling
[ApiController]
public class OrdersController : ControllerBase
{
    [HttpPost]
    public async Task<IActionResult> CreateOrder([FromBody] CreateOrderRequest request)
    {
        try
        {
            var order = await _orderService.CreateOrderAsync(request);
            return CreatedAtAction(nameof(GetOrder), new { id = order.Id }, order);
        }
        catch (ValidationException ex)
        {
            return BadRequest(new { Error = ex.Message, ValidationErrors = ex.Errors });
        }
        catch (InsufficientInventoryException ex)
        {
            return Conflict(new
            {
                Error = ex.Message,
                ProductId = ex.ProductId,
                RequestedQuantity = ex.RequestedQuantity,
                AvailableQuantity = ex.AvailableQuantity
            });
        }
        catch (NotFoundException ex)
        {
            return NotFound(new { Error = ex.Message });
        }
        catch (BusinessException ex)
        {
            return BadRequest(new { Error = ex.Message });
        }
    }
}

// Global Exception Middleware
public class GlobalExceptionMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try
        {
            await next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private async Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var response = context.Response;
        response.ContentType = "application/json";

        var result = exception switch
        {
            ValidationException ex => new {
                Error = "Validation failed",
                Details = ex.Errors,
                StatusCode = 400
            },
            NotFoundException ex => new {
                Error = ex.Message,
                StatusCode = 404
            },
            UnauthorizedException ex => new {
                Error = ex.Message,
                StatusCode = 401
            },
            BusinessException ex => new {
                Error = ex.Message,
                StatusCode = 400
            },
            _ => new {
                Error = "An internal server error occurred",
                StatusCode = 500
            }
        };

        response.StatusCode = result.StatusCode;
        await response.WriteAsync(JsonSerializer.Serialize(result));
    }
}

// Exception Logging and Monitoring
public class ExceptionHandler : IExceptionHandler
{
    public async Task HandleAsync(Exception exception, HttpContext context)
    {
        // Log exception
        _logger.LogError(exception, "Unhandled exception occurred");

        // Track in analytics
        await _analyticsService.TrackExceptionAsync(exception, new
        {
            UserId = _currentUserService.UserId,
            RequestPath = context.Request.Path,
            CorrelationId = _correlationContext.CorrelationId
        });

        // Notify error tracking service
        await _errorTrackingService.CaptureExceptionAsync(exception, context);
    }
}

// Structured Error Responses
public class ErrorResponse
{
    public string Error { get; set; }
    public string Code { get; set; }
    public DateTime Timestamp { get; set; } = DateTime.UtcNow;
    public string CorrelationId { get; set; }
    public Dictionary<string, object> Details { get; set; } = new();
}

✅ Validation Middleware

Comprehensive validation with FluentValidation integration

Usage Examples:

// FluentValidation Validators
public class CreateUserRequestValidator : AbstractValidator<CreateUserRequest>
{
    public CreateUserRequestValidator()
    {
        RuleFor(x => x.Email)
            .NotEmpty().WithMessage("Email is required")
            .EmailAddress().WithMessage("Invalid email format")
            .MustAsync(BeUniqueEmail).WithMessage("Email already exists");

        RuleFor(x => x.FirstName)
            .NotEmpty().WithMessage("First name is required")
            .Length(2, 50).WithMessage("First name must be between 2 and 50 characters");

        RuleFor(x => x.LastName)
            .NotEmpty().WithMessage("Last name is required")
            .Length(2, 50).WithMessage("Last name must be between 2 and 50 characters");

        RuleFor(x => x.Password)
            .NotEmpty().WithMessage("Password is required")
            .MinimumLength(8).WithMessage("Password must be at least 8 characters")
            .Matches(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]")
            .WithMessage("Password must contain uppercase, lowercase, number and special character");

        RuleFor(x => x.Age)
            .GreaterThanOrEqualTo(18).WithMessage("Must be at least 18 years old")
            .LessThanOrEqualTo(120).WithMessage("Age must be realistic");
    }

    private async Task<bool> BeUniqueEmail(string email, CancellationToken cancellationToken)
    {
        return !await _userRepository.ExistsByEmailAsync(email);
    }
}

// Controller with Automatic Validation
[ApiController]
public class UsersController : ControllerBase
{
    [HttpPost]
    [ValidateModel]
    public async Task<IActionResult> CreateUser([FromBody] CreateUserRequest request)
    {
        // Validation is automatically performed by middleware
        // If validation fails, 400 Bad Request is returned automatically

        var user = await _userService.CreateUserAsync(request);
        return CreatedAtAction(nameof(GetUser), new { id = user.Id }, user);
    }
}

// Complex Validation Rules
public class CreateOrderRequestValidator : AbstractValidator<CreateOrderRequest>
{
    public CreateOrderRequestValidator()
    {
        RuleFor(x => x.CustomerId)
            .GreaterThan(0).WithMessage("Valid customer ID is required")
            .MustAsync(CustomerExists).WithMessage("Customer does not exist");

        RuleFor(x => x.Items)
            .NotEmpty().WithMessage("Order must contain at least one item")
            .Must(HaveValidTotalAmount).WithMessage("Order total must be greater than 0");

        RuleForEach(x => x.Items).SetValidator(new OrderItemValidator());

        RuleFor(x => x.ShippingAddress)
            .NotNull().WithMessage("Shipping address is required")
            .SetValidator(new AddressValidator());

        // Conditional validation
        RuleFor(x => x.PromoCode)
            .MustAsync(BeValidPromoCode).WithMessage("Invalid promo code")
            .When(x => !string.IsNullOrEmpty(x.PromoCode));
    }
}

// Custom Validation Attributes
[AttributeUsage(AttributeTargets.Property)]
public class ValidCreditCardAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        if (value is string cardNumber)
        {
            return IsValidCreditCardNumber(cardNumber);
        }
        return false;
    }

    private bool IsValidCreditCardNumber(string cardNumber)
    {
        // Luhn algorithm implementation
        return cardNumber.All(char.IsDigit) &&
               cardNumber.Length >= 13 && cardNumber.Length <= 19;
    }
}

// Model with Validation Attributes
public class PaymentRequest
{
    [Required(ErrorMessage = "Amount is required")]
    [Range(0.01, 999999.99, ErrorMessage = "Amount must be between 0.01 and 999999.99")]
    public decimal Amount { get; set; }

    [Required(ErrorMessage = "Currency is required")]
    [StringLength(3, MinimumLength = 3, ErrorMessage = "Currency must be 3 characters")]
    public string Currency { get; set; }

    [ValidCreditCard(ErrorMessage = "Invalid credit card number")]
    public string CardNumber { get; set; }

    [RegularExpression(@"^(0[1-9]|1[0-2])$", ErrorMessage = "Invalid expiry month")]
    public int ExpiryMonth { get; set; }

    [Range(2024, 2050, ErrorMessage = "Invalid expiry year")]
    public int ExpiryYear { get; set; }
}

// Validation Middleware Configuration
public class ValidationMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        // Pre-validation logic
        var endpoint = context.GetEndpoint();
        var validateAttribute = endpoint?.Metadata.GetMetadata<ValidateModelAttribute>();

        if (validateAttribute != null)
        {
            // Perform validation
            var validationResult = await ValidateRequestAsync(context);
            if (!validationResult.IsValid)
            {
                context.Response.StatusCode = 400;
                await context.Response.WriteAsync(JsonSerializer.Serialize(new
                {
                    Error = "Validation failed",
                    Errors = validationResult.Errors
                }));
                return;
            }
        }

        await next(context);
    }
}

// Manual Validation
public class UserService
{
    public async Task<User> UpdateUserAsync(int userId, UpdateUserRequest request)
    {
        var validator = new UpdateUserRequestValidator();
        var validationResult = await validator.ValidateAsync(request);

        if (!validationResult.IsValid)
        {
            throw new ValidationException(validationResult.Errors);
        }

        var user = await _userRepository.GetByIdAsync(userId);
        user.Update(request.FirstName, request.LastName, request.Email);

        await _userRepository.UpdateAsync(user);
        return user;
    }
}

🏷️ Feature Flags

Dynamic feature management and A/B testing

Usage Examples:

// Basic Feature Flag Usage
public class CheckoutController : ControllerBase
{
    [HttpPost("process")]
    public async Task<IActionResult> ProcessCheckout([FromBody] CheckoutRequest request)
    {
        var useNewCheckoutFlow = await _featureFlagService.IsEnabledAsync("new-checkout-flow");

        if (useNewCheckoutFlow)
        {
            return await ProcessNewCheckoutAsync(request);
        }
        else
        {
            return await ProcessLegacyCheckoutAsync(request);
        }
    }
}

// User-Specific Feature Flags
public class DashboardController : ControllerBase
{
    [HttpGet]
    public async Task<IActionResult> GetDashboard()
    {
        var userId = _currentUserService.UserId;
        var hasAdvancedAnalytics = await _featureFlagService.IsEnabledForUserAsync(
            "advanced-analytics", userId);

        var dashboardData = await _dashboardService.GetBasicDashboardAsync(userId);

        if (hasAdvancedAnalytics)
        {
            dashboardData.AdvancedMetrics = await _analyticsService.GetAdvancedMetricsAsync(userId);
        }

        return Ok(dashboardData);
    }
}

// Feature Flag with Percentage Rollout
var isNewUIEnabled = await _featureFlagService.IsEnabledAsync("new-ui", new FeatureFlagContext
{
    UserId = userId,
    UserSegment = "premium",
    RolloutPercentage = 25 // 25% of users get the new UI
});

// A/B Testing
var abTestVariant = await _featureFlagService.GetVariantAsync("pricing-page-test", new FeatureFlagContext
{
    UserId = userId,
    UserProperties = new Dictionary<string, object>
    {
        ["subscription_tier"] = "premium",
        ["registration_date"] = user.CreatedAt,
        ["country"] = user.Country
    }
});

var pricingPageContent = abTestVariant switch
{
    "variant_a" => await _contentService.GetPricingPageVariantAAsync(),
    "variant_b" => await _contentService.GetPricingPageVariantBAsync(),
    _ => await _contentService.GetDefaultPricingPageAsync()
};

// Feature Flag Attributes
[FeatureFlag("advanced-reporting")]
public class ReportsController : ControllerBase
{
    [HttpGet("advanced")]
    public async Task<IActionResult> GetAdvancedReport()
    {
        // This endpoint is only accessible when the feature flag is enabled
        var report = await _reportingService.GenerateAdvancedReportAsync();
        return Ok(report);
    }
}

// Gradual Rollout
public class FeatureRolloutService
{
    public async Task EnableFeatureGraduallyAsync(string featureName, TimeSpan duration)
    {
        var rolloutSteps = new[]
        {
            new { Percentage = 1, Duration = TimeSpan.FromHours(1) },   // 1% for 1 hour
            new { Percentage = 5, Duration = TimeSpan.FromHours(6) },   // 5% for 6 hours
            new { Percentage = 25, Duration = TimeSpan.FromHours(12) }, // 25% for 12 hours
            new { Percentage = 50, Duration = TimeSpan.FromHours(24) }, // 50% for 24 hours
            new { Percentage = 100, Duration = TimeSpan.Zero }          // 100% (fully enabled)
        };

        foreach (var step in rolloutSteps)
        {
            await _featureFlagService.UpdateRolloutPercentageAsync(featureName, step.Percentage);

            if (step.Duration > TimeSpan.Zero)
            {
                await Task.Delay(step.Duration);
            }
        }
    }
}

// Feature Flag Configuration
public class FeatureFlagConfiguration
{
    public Dictionary<string, FeatureFlagSettings> Features { get; set; } = new()
    {
        ["new-checkout-flow"] = new()
        {
            Enabled = true,
            RolloutPercentage = 50,
            EnabledForSegments = new[] { "beta_users", "premium" },
            EnabledForUsers = new[] { "user123", "user456" }
        },
        ["advanced-analytics"] = new()
        {
            Enabled = true,
            RequiredSubscriptionTier = "premium",
            EnabledCountries = new[] { "US", "CA", "UK" }
        },
        ["experimental-feature"] = new()
        {
            Enabled = false,
            EnabledInEnvironments = new[] { "development", "staging" }
        }
    };
}

// Remote Feature Flag Management
public class RemoteFeatureFlagService
{
    public async Task UpdateFeatureFlagAsync(string featureName, bool enabled)
    {
        await _configurationService.UpdateSettingAsync($"features:{featureName}:enabled", enabled);

        // Notify all application instances of the change
        await _messageBus.PublishAsync(new FeatureFlagUpdatedEvent
        {
            FeatureName = featureName,
            Enabled = enabled,
            UpdatedAt = DateTime.UtcNow
        });
    }
}

// Feature Flag Analytics
public class FeatureFlagAnalytics
{
    public async Task TrackFeatureFlagUsageAsync(string featureName, bool enabled, string userId)
    {
        await _analyticsService.TrackEventAsync("feature_flag_evaluated", new
        {
            FeatureName = featureName,
            Enabled = enabled,
            UserId = userId,
            Timestamp = DateTime.UtcNow
        });
    }

    public async Task<FeatureFlagMetrics> GetFeatureFlagMetricsAsync(string featureName, TimeRange timeRange)
    {
        return await _analyticsService.GetMetricsAsync<FeatureFlagMetrics>(
            $"feature_flags.{featureName}", timeRange);
    }
}

⚙️ Configuration

appsettings.json Configuration

{
  "Marventa": {
    // 💡 SMART DEFAULTS: All features are FALSE by default
    // Only enable what you actually need!

    // 🎯 MINIMAL SETUP (just enable basic features)
    "EnableStorage": true,              // Basic file operations
    "EnableSecurity": true,             // Basic security
    "EnableValidation": true,           // Input validation

    // 🎯 PRODUCTION SETUP (enable production features)
    // Uncomment these for production-ready apps:
    // "EnableJWT": true,               // JWT authentication
    // "EnableCaching": true,           // Performance boost
    // "EnableRateLimiting": true,      // API protection
    // "EnableHealthChecks": true,      // Monitoring
    // "EnableLogging": true,           // Structured logging
    // "EnableHttpClient": true,        // External API calls
    // "EnableExceptionHandling": true, // Global error handling

    // 🎯 ENTERPRISE SETUP (enable enterprise features)
    // Uncomment these for enterprise applications:
    // "EnableFileProcessor": true,     // Image processing
    // "EnableCDN": true,               // Content delivery
    // "EnableMetadata": true,          // File metadata
    // "EnableMultiTenancy": true,      // Multi-tenant support
    // "EnableEventDriven": true,       // Event-driven architecture
    // "EnableCQRS": true,              // Command Query separation
    // "EnableRepository": true,        // Data access abstraction
    // "EnableDistributedLocking": true, // Distributed locks
    // "EnableIdempotency": true,       // Safe retries
    // "EnableAnalytics": true,         // Analytics tracking
    // "EnableObservability": true,     // Distributed tracing
    // "EnableMessaging": true,         // Message bus
    // "EnableEmail": true,             // Email notifications
    // "EnableSMS": true,               // SMS notifications
    // "EnableSearch": true,            // Search functionality
    // "EnableML": true,                // AI/ML features
    // "EnableBackgroundJobs": true,    // Job scheduling
    // "EnableProjections": true,       // Event sourcing projections
    // "EnableECommerce": true,         // E-commerce features
    // "EnablePayments": true,          // Payment processing
    // "EnableShipping": true,          // Shipping management
    // "EnableFraudDetection": true,    // Fraud detection
    // "EnableVersioning": true,        // API versioning
    // "EnableFeatureFlags": true,      // Feature flags
    // "EnableSagas": true,             // Saga orchestration
    // "EnableDatabaseSeeding": true,   // Database initialization
    // "EnableApiKeys": true,           // API key authentication
    // "EnableEncryption": true,        // Data encryption

    "StorageOptions": {
      "Provider": "AzureBlob",
      "ConnectionString": "DefaultEndpointsProtocol=https;...",
      "DefaultContainer": "files",
      "EnableEncryption": true,
      "MaxFileSizeBytes": 104857600
    },

    "FileProcessorOptions": {
      "Provider": "ImageSharp",
      "DefaultImageQuality": 85,
      "MaxFileSizeBytes": 52428800,
      "SupportedFormats": ["jpg", "jpeg", "png", "webp", "gif"],
      "DefaultThumbnailSizes": [
        { "Name": "small", "Width": 150, "Height": 150 },
        { "Name": "medium", "Width": 300, "Height": 300 },
        { "Name": "large", "Width": 600, "Height": 600 }
      ]
    },

    "CDNOptions": {
      "Provider": "CloudFlare",
      "Endpoint": "https://cdn.example.com",
      "ApiKey": "${CLOUDFLARE_API_KEY}",
      "DefaultCacheTTL": 86400,
      "EnableCompression": true
    },

    "MLOptions": {
      "Provider": "AzureAI",
      "ApiEndpoint": "https://cognitiveservices.azure.com",
      "ApiKey": "${AZURE_AI_KEY}",
      "MinConfidenceThreshold": 0.7,
      "MaxConcurrentRequests": 10
    },

    "MetadataOptions": {
      "Provider": "MongoDB",
      "ConnectionString": "mongodb://localhost:27017",
      "DatabaseName": "FileMetadata",
      "EnableFullTextSearch": true
    },

    // 🔐 Security & Authentication Options
    "SecurityOptions": {
      "DefaultAuthenticationScheme": "Bearer",
      "EnablePasswordPolicy": true,
      "MinPasswordLength": 8
    },

    "JwtOptions": {
      "SecretKey": "${JWT_SECRET_KEY}",
      "Issuer": "YourApp",
      "Audience": "YourApp",
      "ExpirationMinutes": 60,
      "RefreshTokenExpirationDays": 7
    },

    "ApiKeyOptions": {
      "HeaderName": "X-API-Key",
      "EnablePermissions": true,
      "DefaultPermissions": ["read"]
    },

    "EncryptionOptions": {
      "Algorithm": "AES256",
      "KeySize": 256,
      "EnableFileEncryption": false
    },

    // 🏢 Multi-Tenancy & Architecture Options
    "MultiTenancyOptions": {
      "TenantResolutionStrategy": "Header",
      "DefaultTenantId": "default",
      "EnableTenantScopedServices": true
    },

    "EventDrivenOptions": {
      "Provider": "InMemory",
      "EnableDomainEvents": true,
      "EnableIntegrationEvents": true
    },

    "CQRSOptions": {
      "EnableCommandValidation": true,
      "EnableQueryCaching": false,
      "DefaultTimeout": 30000
    },

    "SagaOptions": {
      "Provider": "InMemory",
      "EnableCompensation": true,
      "DefaultTimeout": 300000
    },

    "RepositoryOptions": {
      "EnableUnitOfWork": true,
      "EnableChangeTracking": true,
      "DefaultPageSize": 50
    },

    // ⚡ Performance & Scalability Options
    "CachingOptions": {
      "Provider": "InMemory",
      "DefaultExpirationMinutes": 30,
      "EnableDistributedCache": false
    },

    "RateLimitingOptions": {
      "GlobalLimitPerMinute": 1000,
      "PerUserLimitPerMinute": 60,
      "EnableTenantLimiting": false
    },

    "DistributedLockingOptions": {
      "Provider": "Redis",
      "DefaultLockTimeoutMinutes": 5,
      "EnableLockExtension": true
    },

    "IdempotencyOptions": {
      "EnableRequestIdempotency": true,
      "DefaultExpirationHours": 24,
      "KeyHeaderName": "Idempotency-Key"
    },

    // 📊 Analytics & Monitoring Options
    "AnalyticsOptions": {
      "Provider": "InMemory",
      "EnableRealTimeTracking": false,
      "BatchSize": 100
    },

    "HealthCheckOptions": {
      "EnableDatabaseCheck": true,
      "EnableMemoryCheck": true,
      "TimeoutSeconds": 30
    },

    "ObservabilityOptions": {
      "ServiceName": "YourApp",
      "EnableDistributedTracing": false,
      "SamplingRatio": 0.1
    },

    "LoggingOptions": {
      "MinimumLevel": "Information",
      "EnableStructuredLogging": true,
      "EnableCorrelationId": true
    },

    // 📧 Messaging & Communication Options
    "MessagingOptions": {
      "Provider": "InMemory",
      "RetryAttempts": 3,
      "EnableDeadLetterQueue": false
    },

    "EmailOptions": {
      "Provider": "SMTP",
      "FromEmail": "noreply@yourapp.com",
      "EnableTracking": false
    },

    "SmsOptions": {
      "Provider": "Console",
      "EnableDeliveryReceipts": false,
      "DefaultTimeout": 30
    },

    // 🔍 Search & AI/ML Options
    "SearchOptions": {
      "Provider": "InMemory",
      "DefaultIndex": "documents",
      "EnableAutoIndexing": false
    },

    // ⏱️ Background & Data Processing Options
    "BackgroundJobOptions": {
      "Provider": "InMemory",
      "MaxConcurrentJobs": 5,
      "EnableJobRetry": true
    },

    "DatabaseSeedingOptions": {
      "EnableSeeding": true,
      "SeedInProduction": false,
      "SeedDataPath": "Data/SeedData"
    },

    "ProjectionOptions": {
      "EnableRealTimeProjections": false,
      "BatchSize": 1000,
      "SnapshotIntervalHours": 1
    },

    // 🛒 E-Commerce & Business Options
    "ECommerceOptions": {
      "EnableInventoryTracking": true,
      "EnablePricing": true,
      "DefaultCurrency": "USD"
    },

    "PaymentOptions": {
      "DefaultGateway": "Console",
      "EnableTestMode": true,
      "EnableRefunds": true
    },

    "ShippingOptions": {
      "DefaultCarrier": "Console",
      "EnableTracking": false,
      "EnableRateCalculation": false
    },

    "FraudDetectionOptions": {
      "EnableRealTimeChecking": false,
      "DefaultRiskThreshold": 0.7,
      "EnableMLPrediction": false
    },

    // 🌐 API & Web Management Options
    "VersioningOptions": {
      "DefaultVersion": "1.0",
      "EnableHeaderVersioning": true,
      "EnableQueryVersioning": true
    },

    "HttpClientOptions": {
      "DefaultTimeoutSeconds": 30,
      "MaxRetries": 3,
      "EnableCircuitBreaker": false
    },

    "ExceptionHandlingOptions": {
      "EnableGlobalExceptionHandler": true,
      "EnableDetailedErrors": false,
      "LogExceptions": true
    },

    "ValidationOptions": {
      "EnableFluentValidation": true,
      "EnableDataAnnotations": true,
      "StopOnFirstFailure": false
    },

    // ⚙️ Configuration & Features Options
    "FeatureFlagOptions": {
      "Provider": "InMemory",
      "EnableRemoteConfiguration": false,
      "EnableAnalytics": false
    }
  }
}

Environment Variables

# Storage
AZURE_STORAGE_CONNECTION_STRING="DefaultEndpointsProtocol=https;..."
AWS_ACCESS_KEY_ID="your-access-key"
AWS_SECRET_ACCESS_KEY="your-secret-key"

# CDN
CLOUDFLARE_API_KEY="your-api-key"
CLOUDFLARE_ZONE_ID="your-zone-id"

# AI/ML
AZURE_AI_KEY="your-cognitive-services-key"
OPENAI_API_KEY="your-openai-key"

# Metadata
MONGODB_CONNECTION_STRING="mongodb://localhost:27017"

🧪 Testing

Built-in mock services for comprehensive testing:

// Test configuration
services.AddMarventaFramework(options =>
{
    options.StorageOptions.Provider = StorageProvider.Mock;
    options.FileProcessorOptions.Provider = FileProcessorProvider.Mock;
    options.CDNOptions.Provider = CDNProvider.Mock;
    options.MLOptions.Provider = MLProvider.Mock;
    options.MetadataOptions.Provider = MetadataProvider.Mock;
});

// Example test
[Fact]
public async Task UploadFile_Should_ReturnSuccess()
{
    // Arrange
    var fileContent = new byte[] { 0x48, 0x65, 0x6C, 0x6C, 0x6F };
    using var stream = new MemoryStream(fileContent);

    // Act
    var result = await _storage.UploadFileAsync(stream, "test.txt", "text/plain");

    // Assert
    result.Should().NotBeNull();
    result.Success.Should().BeTrue();
    result.FileId.Should().NotBeNullOrEmpty();
}

Test Coverage: 39 comprehensive tests covering all features


✅ Best Practices

1. Resource Management

// Always dispose streams
using var fileStream = File.OpenRead(filePath);
var result = await _storage.UploadFileAsync(fileStream, fileName, contentType);

// Use using statements for automatic disposal
using var processedStream = result.ProcessedImage;

2. Error Handling

try
{
    var result = await _storage.UploadFileAsync(stream, fileName, contentType);
    if (!result.Success)
    {
        _logger.LogError("Upload failed: {Error}", result.ErrorMessage);
        return BadRequest(result.ErrorMessage);
    }
}
catch (Exception ex)
{
    _logger.LogError(ex, "Upload operation failed");
    return StatusCode(500, "Internal server error");
}

3. Performance Optimization

// Use cancellation tokens
var cts = new CancellationTokenSource(TimeSpan.FromMinutes(5));
var result = await _processor.ProcessImageAsync(stream, options, cts.Token);

// Enable parallel processing for bulk operations
var files = GetFiles();
var results = await _storage.BulkUploadAsync(files);

4. Security

// Validate file types
var allowedTypes = new[] { "image/jpeg", "image/png", "image/webp" };
if (!allowedTypes.Contains(file.ContentType))
{
    return BadRequest("File type not allowed");
}

// Check file size
if (file.Length > 10 * 1024 * 1024) // 10MB
{
    return BadRequest("File too large");
}

// Enable encryption for sensitive files
options.StorageOptions.EnableEncryption = true;

📦 Available Packages

Package Purpose Dependencies
Marventa.Framework Complete solution All features included
Marventa.Framework.Core Models & Interfaces No dependencies
Marventa.Framework.Infrastructure Service implementations Core + External libraries
Marventa.Framework.Web ASP.NET integration Infrastructure

💡 Why Choose Marventa Framework?

Complete Enterprise Solution - 47 features in one framework ✅ Modular Design - Enable only what you need, pay for what you use ✅ Production Ready - Battle-tested in enterprise environments ✅ Provider Agnostic - Switch providers without code changes ✅ Clean Architecture - SOLID principles, CQRS, Event Sourcing ✅ Multi-Tenant Ready - Complete tenant isolation and management ✅ Security First - JWT, API Keys, Encryption, Rate Limiting ✅ Event-Driven - Domain events, Integration events, Message Bus ✅ Performance Optimized - Caching, Distributed locks, Background jobs ✅ Developer Friendly - Intuitive APIs with extensive examples ✅ Comprehensive Testing - 39 tests with full mock support ✅ Zero Build Errors - Professional, production-ready


📄 License

This project is licensed under the MIT License - see the LICENSE file for details.


<div align="center"> <strong>Built with ❤️ for the .NET Community</strong> <br> <sub>The complete enterprise .NET framework - from file management to full-scale applications</sub> </div>

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
5.2.0 229 10/13/2025 5.2.0 is deprecated because it is no longer maintained.
5.1.0 277 10/5/2025 5.1.0 is deprecated because it is no longer maintained.
5.0.0 184 10/4/2025 5.0.0 is deprecated because it is no longer maintained.
4.6.0 196 10/3/2025 4.6.0 is deprecated because it is no longer maintained.
4.5.5 215 10/2/2025 4.5.5 is deprecated because it is no longer maintained.
4.5.4 210 10/2/2025 4.5.4 is deprecated because it is no longer maintained.
4.5.3 208 10/2/2025 4.5.3 is deprecated because it is no longer maintained.
4.5.2 209 10/2/2025 4.5.2 is deprecated because it is no longer maintained.
4.5.1 211 10/2/2025 4.5.1 is deprecated because it is no longer maintained.
4.5.0 212 10/2/2025 4.5.0 is deprecated because it is no longer maintained.
4.4.0 218 10/1/2025 4.4.0 is deprecated because it is no longer maintained.
4.3.0 217 10/1/2025 4.3.0 is deprecated because it is no longer maintained.
4.2.0 218 10/1/2025 4.2.0 is deprecated because it is no longer maintained.
4.1.0 210 10/1/2025 4.1.0 is deprecated because it is no longer maintained.
4.0.2 218 10/1/2025 4.0.2 is deprecated because it is no longer maintained.
4.0.1 210 10/1/2025 4.0.1 is deprecated because it is no longer maintained.
4.0.0 286 9/30/2025 4.0.0 is deprecated because it is no longer maintained.
3.5.2 219 9/30/2025 3.5.2 is deprecated because it is no longer maintained.
3.5.1 250 9/30/2025 3.5.1 is deprecated because it is no longer maintained.
3.4.1 254 9/30/2025 3.4.1 is deprecated because it is no longer maintained.
3.4.0 249 9/30/2025 3.4.0 is deprecated because it is no longer maintained.
3.3.2 261 9/30/2025 3.3.2 is deprecated because it is no longer maintained.
3.2.0 253 9/30/2025 3.2.0 is deprecated because it is no longer maintained.
3.1.0 252 9/29/2025 3.1.0 is deprecated because it is no longer maintained.
3.0.1 251 9/29/2025 3.0.1 is deprecated because it is no longer maintained.
3.0.1-preview-20250929165802 245 9/29/2025 3.0.1-preview-20250929165802 is deprecated because it is no longer maintained.
3.0.0 248 9/29/2025 3.0.0 is deprecated because it is no longer maintained.
3.0.0-preview-20250929164242 251 9/29/2025 3.0.0-preview-20250929164242 is deprecated because it is no longer maintained.
3.0.0-preview-20250929162455 248 9/29/2025 3.0.0-preview-20250929162455 is deprecated because it is no longer maintained.
2.12.0-preview-20250929161039 242 9/29/2025 2.12.0-preview-20250929161039 is deprecated because it is no longer maintained.
2.11.0 253 9/29/2025 2.11.0 is deprecated because it is no longer maintained.
2.10.0 253 9/29/2025 2.10.0 is deprecated because it is no longer maintained.
2.9.0 247 9/29/2025 2.9.0 is deprecated because it is no longer maintained.
2.8.0 249 9/29/2025 2.8.0 is deprecated because it is no longer maintained.
2.7.0 260 9/29/2025 2.7.0 is deprecated because it is no longer maintained.
2.6.0 254 9/28/2025 2.6.0 is deprecated because it is no longer maintained.
2.5.0 260 9/28/2025 2.5.0 is deprecated because it is no longer maintained.
2.4.0 252 9/28/2025 2.4.0 is deprecated because it is no longer maintained.
2.3.0 253 9/28/2025 2.3.0 is deprecated because it is no longer maintained.
2.2.0 255 9/28/2025 2.2.0 is deprecated because it is no longer maintained.
2.1.0 253 9/26/2025 2.1.0 is deprecated because it is no longer maintained.
2.0.9 257 9/26/2025 2.0.9 is deprecated because it is no longer maintained.
2.0.5 250 9/25/2025 2.0.5 is deprecated because it is no longer maintained.
2.0.4 256 9/25/2025 2.0.4 is deprecated because it is no longer maintained.
2.0.3 261 9/25/2025 2.0.3 is deprecated because it is no longer maintained.
2.0.1 257 9/25/2025 2.0.1 is deprecated because it is no longer maintained.
2.0.0 258 9/25/2025 2.0.0 is deprecated because it is no longer maintained.
1.1.2 334 9/24/2025 1.1.2 is deprecated because it is no longer maintained.
1.1.1 335 9/24/2025 1.1.1 is deprecated because it is no longer maintained.
1.1.0 253 9/24/2025 1.1.0 is deprecated because it is no longer maintained.
1.0.0 258 9/24/2025 1.0.0 is deprecated because it is no longer maintained.

v2.4.0: 🚀 MAJOR UPDATE: True modular architecture implementation! Now features 47 enterprise-grade features with complete enable/disable control. Fixed extension method inconsistencies - AddMarventaFramework(options) now fully functional with smart defaults. Eliminated unused files and achieved perfect README-code alignment. Zero build warnings, production-ready modular framework with pay-as-you-use architecture. All features documented with working code examples!