
Previous article: ASP.NET Core Configuration & Secrets Mastery: Complete Security Guide (Part- 17 of 40)
Table of Contents
The Design Patterns Renaissance
Repository Pattern: Data Access Abstraction
Unit of Work: Transaction Management
Singleton Pattern: Shared Instance Management
Factory Pattern: Object Creation Magic
Strategy Pattern: Algorithmic Flexibility
Decorator Pattern: Behavior Extension
Observer Pattern: Event-Driven Architecture
Mediator Pattern: Decoupled Communication
Pattern Combinations in Real Applications
Testing Patterns with xUnit
Performance Considerations
Anti-Patterns to Avoid
Conclusion
1. The Design Patterns Renaissance
Why Design Patterns Matter in Modern Development
Design patterns are proven solutions to common software design problems. In ASP.NET Core, they provide:
Maintainability : Code that's easy to understand and modify
Scalability : Architecture that grows with your application
Testability : Designs that support comprehensive testing
Flexibility : Systems that adapt to changing requirements
Real-World Analogy: The Construction Blueprint
Think of design patterns like architectural blueprints in construction:
// Without patterns - like building without blueprintspublic class MessyController : ControllerBase{
private readonly MyDbContext _context;
private readonly IConfiguration _config;
private readonly ILogger _logger;
public IActionResult GetUser(int id)
{
// Direct database access
// Business logic mixed with data access
// Hard to test and maintain
var user = _context.Users.Find(id);
if (user == null) return NotFound();
// Validation logic here
// Email sending logic here
// Logging scattered everywhere
return Ok(user);
}}
// With patterns - like following proven architectural planspublic class CleanController : ControllerBase{
private readonly IUserRepository _userRepository;
private readonly IUserService _userService;
public CleanController(IUserRepository userRepository, IUserService userService)
{
_userRepository = userRepository;
_userService = userService;
}
public async Task<IActionResult> GetUser(int id)
{
var user = await _userRepository.GetByIdAsync(id);
if (user == null) return NotFound();
return Ok(user);
}}
The Pattern Categories in ASP.NET Core
| Category | Purpose | ASP.NET Core Examples |
|---|---|---|
| Creational | Object creation mechanisms | Singleton, Factory, Builder |
| Structural | Object composition | Decorator, Adapter, Composite |
| Behavioral | Object interaction & responsibility | Strategy, Observer, Mediator |
| Architectural | Application structure | Repository, Unit of Work, CQRS |
2. Repository Pattern: Data Access Abstraction
The Problem: Tight Coupling with Data Access
Without the Repository Pattern, controllers become tightly coupled to Entity Framework:
// ❌ Problem: Controller coupled to Entity Frameworkpublic class ProductController : ControllerBase{
private readonly ApplicationDbContext _context;
public ProductController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> GetProducts()
{
// Direct EF Core usage throughout controller
var products = await _context.Products
.Include(p => p.Category)
.Where(p => p.IsActive)
.ToListAsync();
return Ok(products);
}
// Multiple actions with similar data access logic
// Hard to test without database
// Difficult to change data storage technology}
Repository Pattern Solution
The Repository pattern mediates between the domain and data mapping layers, acting like an in-memory domain object collection.
Step 1. Define Repository Interfaces
// Interfaces/IRepository.csusing System.Linq.Expressions;
namespace ECommercePatterns.Interfaces{
/// <summary>
/// Base repository interface with common CRUD operations
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
public interface IRepository<T> where T : class
{
Task<T?> GetByIdAsync(int id);
Task<IEnumerable<T>> GetAllAsync();
Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate);
Task<T> AddAsync(T entity);
Task UpdateAsync(T entity);
Task DeleteAsync(T entity);
Task<bool> ExistsAsync(int id);
Task<int> CountAsync(Expression<Func<T, bool>>? predicate = null);
}
/// <summary>
/// Extended repository with pagination and advanced queries
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
public interface IExtendedRepository<T> : IRepository<T> where T : class
{
Task<PagedResult<T>> GetPagedAsync(int page, int pageSize);
Task<PagedResult<T>> GetPagedAsync(Expression<Func<T, bool>> predicate, int page, int pageSize);
Task<IEnumerable<T>> GetAsync(ISpecification<T> specification);
Task<T?> GetSingleAsync(Expression<Func<T, bool>> predicate);
}
/// <summary>
/// Product-specific repository operations
/// </summary>
public interface IProductRepository : IExtendedRepository<Product>
{
Task<IEnumerable<Product>> GetProductsByCategoryAsync(int categoryId);
Task<IEnumerable<Product>> GetActiveProductsAsync();
Task<IEnumerable<Product>> SearchProductsAsync(string searchTerm);
Task UpdateStockAsync(int productId, int quantity);
Task<IEnumerable<Product>> GetProductsWithCategoryAsync();
Task<PagedResult<Product>> GetProductsPagedWithCategoryAsync(int page, int pageSize);
}
/// <summary>
/// Specification pattern for complex queries
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
public interface ISpecification<T>
{
Expression<Func<T, bool>> Criteria { get; }
List<Expression<Func<T, object>>> Includes { get; }
Expression<Func<T, object>> OrderBy { get; }
Expression<Func<T, object>> OrderByDescending { get; }
int Take { get; }
int Skip { get; }
bool IsPagingEnabled { get; }
}
/// <summary>
/// Pagination result wrapper
/// </summary>
/// <typeparam name="T">Item type</typeparam>
public class PagedResult<T>
{
public IEnumerable<T> Items { get; set; } = new List<T>();
public int TotalCount { get; set; }
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
public bool HasPrevious => PageNumber > 1;
public bool HasNext => PageNumber < TotalPages;
}}
Step 2. Implement Generic Repository
// Repositories/Repository.csusing Microsoft.EntityFrameworkCore;using System.Linq.Expressions;
namespace ECommercePatterns.Repositories{
/// <summary>
/// Generic repository implementation using Entity Framework Core
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _context;
protected readonly DbSet<T> _dbSet;
public Repository(DbContext context)
{
_context = context;
_dbSet = context.Set<T>();
}
public virtual async Task<T?> GetByIdAsync(int id)
{
return await _dbSet.FindAsync(id);
}
public virtual async Task<IEnumerable<T>> GetAllAsync()
{
return await _dbSet.ToListAsync();
}
public virtual async Task<IEnumerable<T>> FindAsync(Expression<Func<T, bool>> predicate)
{
return await _dbSet.Where(predicate).ToListAsync();
}
public virtual async Task<T> AddAsync(T entity)
{
await _dbSet.AddAsync(entity);
await _context.SaveChangesAsync();
return entity;
}
public virtual async Task UpdateAsync(T entity)
{
_dbSet.Update(entity);
await _context.SaveChangesAsync();
}
public virtual async Task DeleteAsync(T entity)
{
_dbSet.Remove(entity);
await _context.SaveChangesAsync();
}
public virtual async Task<bool> ExistsAsync(int id)
{
var entity = await GetByIdAsync(id);
return entity != null;
}
public virtual async Task<int> CountAsync(Expression<Func<T, bool>>? predicate = null)
{
return predicate == null
? await _dbSet.CountAsync()
: await _dbSet.CountAsync(predicate);
}
}
/// <summary>
/// Extended repository with advanced features
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
public class ExtendedRepository<T> : Repository<T>, IExtendedRepository<T> where T : class
{
public ExtendedRepository(DbContext context) : base(context)
{
}
public virtual async Task<PagedResult<T>> GetPagedAsync(int page, int pageSize)
{
return await GetPagedAsync(x => true, page, pageSize);
}
public virtual async Task<PagedResult<T>> GetPagedAsync(Expression<Func<T, bool>> predicate, int page, int pageSize)
{
var query = _dbSet.Where(predicate);
var totalCount = await query.CountAsync();
var items = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return new PagedResult<T>
{
Items = items,
TotalCount = totalCount,
PageNumber = page,
PageSize = pageSize
};
}
public virtual async Task<IEnumerable<T>> GetAsync(ISpecification<T> specification)
{
return await ApplySpecification(specification).ToListAsync();
}
public virtual async Task<T?> GetSingleAsync(Expression<Func<T, bool>> predicate)
{
return await _dbSet.FirstOrDefaultAsync(predicate);
}
private IQueryable<T> ApplySpecification(ISpecification<T> specification)
{
return SpecificationEvaluator<T>.GetQuery(_dbSet.AsQueryable(), specification);
}
}
/// <summary>
/// Specification evaluator for applying specifications to queries
/// </summary>
/// <typeparam name="T">Entity type</typeparam>
public static class SpecificationEvaluator<T> where T : class
{
public static IQueryable<T> GetQuery(IQueryable<T> inputQuery, ISpecification<T> specification)
{
var query = inputQuery;
// Apply criteria (where clause)
if (specification.Criteria != null)
{
query = query.Where(specification.Criteria);
}
// Apply includes (eager loading)
query = specification.Includes.Aggregate(query,
(current, include) => current.Include(include));
// Apply ordering
if (specification.OrderBy != null)
{
query = query.OrderBy(specification.OrderBy);
}
else if (specification.OrderByDescending != null)
{
query = query.OrderByDescending(specification.OrderByDescending);
}
// Apply paging
if (specification.IsPagingEnabled)
{
query = query.Skip(specification.Skip)
.Take(specification.Take);
}
return query;
}
}}
Step 3: Implement Specific Repository
// Repositories/ProductRepository.csusing Microsoft.EntityFrameworkCore;using ECommercePatterns.Interfaces;using ECommercePatterns.Entities;
namespace ECommercePatterns.Repositories{
/// <summary>
/// Product-specific repository implementation
/// </summary>
public class ProductRepository : ExtendedRepository<Product>, IProductRepository
{
private readonly ECommerceContext _context;
public ProductRepository(ECommerceContext context) : base(context)
{
_context = context;
}
public async Task<IEnumerable<Product>> GetProductsByCategoryAsync(int categoryId)
{
return await _context.Products
.Include(p => p.Category)
.Where(p => p.CategoryId == categoryId && p.IsActive)
.ToListAsync();
}
public async Task<IEnumerable<Product>> GetActiveProductsAsync()
{
return await _context.Products
.Include(p => p.Category)
.Where(p => p.IsActive)
.OrderBy(p => p.Name)
.ToListAsync();
}
public async Task<IEnumerable<Product>> SearchProductsAsync(string searchTerm)
{
return await _context.Products
.Include(p => p.Category)
.Where(p => p.IsActive &&
(p.Name.Contains(searchTerm) ||
p.Description.Contains(searchTerm) ||
p.Category.Name.Contains(searchTerm)))
.ToListAsync();
}
public async Task UpdateStockAsync(int productId, int quantity)
{
var product = await _context.Products.FindAsync(productId);
if (product != null)
{
product.StockQuantity += quantity;
product.UpdatedAt = DateTime.UtcNow;
await _context.SaveChangesAsync();
}
}
public async Task<IEnumerable<Product>> GetProductsWithCategoryAsync()
{
return await _context.Products
.Include(p => p.Category)
.Where(p => p.IsActive)
.ToListAsync();
}
public async Task<PagedResult<Product>> GetProductsPagedWithCategoryAsync(int page, int pageSize)
{
var query = _context.Products
.Include(p => p.Category)
.Where(p => p.IsActive)
.OrderBy(p => p.Name);
var totalCount = await query.CountAsync();
var items = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
return new PagedResult<Product>
{
Items = items,
TotalCount = totalCount,
PageNumber = page,
PageSize = pageSize
};
}
}}
Step 4. Entity Models
// Entities/Product.csusing System.ComponentModel.DataAnnotations;using System.ComponentModel.DataAnnotations.Schema;
namespace ECommercePatterns.Entities{
/// <summary>
/// Product entity representing items in the e-commerce system
/// </summary>
public class Product
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; } = string.Empty;
[StringLength(500)]
public string Description { get; set; } = string.Empty;
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
public int StockQuantity { get; set; }
public bool IsActive { get; set; } = true;
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; } = null!;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
// Business logic methods
public bool IsInStock() => StockQuantity > 0;
public bool CanOrderQuantity(int quantity) => IsActive && StockQuantity >= quantity;
public void ReduceStock(int quantity)
{
if (quantity <= 0)
throw new ArgumentException("Quantity must be positive", nameof(quantity));
if (StockQuantity < quantity)
throw new InvalidOperationException("Insufficient stock");
StockQuantity -= quantity;
UpdatedAt = DateTime.UtcNow;
}
}
/// <summary>
/// Product category entity
/// </summary>
public class Category
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; } = string.Empty;
[StringLength(200)]
public string Description { get; set; } = string.Empty;
public bool IsActive { get; set; } = true;
public virtual ICollection<Product> Products { get; set; } = new List<Product>();
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
}}
Step 5. Database Context
// Data/ECommerceContext.csusing Microsoft.EntityFrameworkCore;using ECommercePatterns.Entities;
namespace ECommercePatterns.Data{
/// <summary>
/// Entity Framework database context for e-commerce application
/// </summary>
public class ECommerceContext : DbContext
{
public ECommerceContext(DbContextOptions<ECommerceContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; } = null!;
public DbSet<Category> Categories { get; set; } = null!;
public DbSet<Order> Orders { get; set; } = null!;
public DbSet<OrderItem> OrderItems { get; set; } = null!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Product configuration
modelBuilder.Entity<Product>(entity =>
{
entity.HasKey(p => p.Id);
entity.Property(p => p.Name).IsRequired().HasMaxLength(100);
entity.Property(p => p.Description).HasMaxLength(500);
entity.Property(p => p.Price).HasColumnType("decimal(18,2)");
entity.Property(p => p.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
entity.Property(p => p.UpdatedAt).HasDefaultValueSql("GETUTCDATE()");
// Indexes
entity.HasIndex(p => p.Name);
entity.HasIndex(p => p.CategoryId);
entity.HasIndex(p => p.IsActive);
// Relationships
entity.HasOne(p => p.Category)
.WithMany(c => c.Products)
.HasForeignKey(p => p.CategoryId)
.OnDelete(DeleteBehavior.Restrict);
});
// Category configuration
modelBuilder.Entity<Category>(entity =>
{
entity.HasKey(c => c.Id);
entity.Property(c => c.Name).IsRequired().HasMaxLength(50);
entity.Property(c => c.Description).HasMaxLength(200);
entity.Property(c => c.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
// Indexes
entity.HasIndex(c => c.Name).IsUnique();
});
// Seed data
modelBuilder.Entity<Category>().HasData(
new Category { Id = 1, Name = "Electronics", Description = "Electronic devices and accessories" },
new Category { Id = 2, Name = "Books", Description = "Books and educational materials" },
new Category { Id = 3, Name = "Clothing", Description = "Apparel and fashion items" }
);
modelBuilder.Entity<Product>().HasData(
new Product
{
Id = 1,
Name = "Wireless Mouse",
Description = "Ergonomic wireless mouse",
Price = 29.99m,
StockQuantity = 50,
CategoryId = 1
},
new Product
{
Id = 2,
Name = "Programming Book",
Description = "Advanced C# programming guide",
Price = 45.99m,
StockQuantity = 25,
CategoryId = 2
}
);
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
// Automatic update of UpdatedAt timestamp
var entries = ChangeTracker.Entries()
.Where(e => e.Entity is Product &&
(e.State == EntityState.Modified || e.State == EntityState.Added));
foreach (var entityEntry in entries)
{
if (entityEntry.State == EntityState.Modified)
{
((Product)entityEntry.Entity).UpdatedAt = DateTime.UtcNow;
}
}
return await base.SaveChangesAsync(cancellationToken);
}
}}
Step 6: Clean Controller Using Repository
// Controllers/ProductsController.csusing Microsoft.AspNetCore.Mvc;using ECommercePatterns.Interfaces;using ECommercePatterns.Entities;
namespace ECommercePatterns.Controllers{
/// <summary>
/// Products controller using Repository pattern for clean data access
/// </summary>
[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class ProductsController : ControllerBase
{
private readonly IProductRepository _productRepository;
private readonly ILogger<ProductsController> _logger;
public ProductsController(IProductRepository productRepository, ILogger<ProductsController> logger)
{
_productRepository = productRepository;
_logger = logger;
}
/// <summary>
/// Get all active products with pagination
/// </summary>
[HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<PagedResult<Product>>> GetProducts(
[FromQuery] int page = 1,
[FromQuery] int pageSize = 10)
{
_logger.LogInformation("Retrieving products page {Page} with size {PageSize}", page, pageSize);
var result = await _productRepository.GetProductsPagedWithCategoryAsync(page, pageSize);
return Ok(result);
}
/// <summary>
/// Get product by ID
/// </summary>
[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<Product>> GetProduct(int id)
{
var product = await _productRepository.GetByIdAsync(id);
if (product == null)
{
_logger.LogWarning("Product with ID {ProductId} not found", id);
return NotFound();
}
return Ok(product);
}
/// <summary>
/// Search products by name or description
/// </summary>
[HttpGet("search")]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<ActionResult<IEnumerable<Product>>> SearchProducts([FromQuery] string term)
{
if (string.IsNullOrWhiteSpace(term))
{
return BadRequest("Search term is required");
}
var products = await _productRepository.SearchProductsAsync(term);
return Ok(products);
}
/// <summary>
/// Create a new product
/// </summary>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<ActionResult<Product>> CreateProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
try
{
var createdProduct = await _productRepository.AddAsync(product);
_logger.LogInformation("Created product with ID {ProductId}", createdProduct.Id);
return CreatedAtAction(nameof(GetProduct), new { id = createdProduct.Id }, createdProduct);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error creating product");
return StatusCode(500, "An error occurred while creating the product");
}
}
/// <summary>
/// Update product stock
/// </summary>
[HttpPatch("{id}/stock")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<IActionResult> UpdateStock(int id, [FromBody] StockUpdateRequest request)
{
try
{
await _productRepository.UpdateStockAsync(id, request.Quantity);
_logger.LogInformation("Updated stock for product {ProductId} by {Quantity}", id, request.Quantity);
return Ok();
}
catch (ArgumentException ex)
{
_logger.LogWarning(ex, "Invalid stock update request for product {ProductId}", id);
return BadRequest(ex.Message);
}
}
}
/// <summary>
/// Stock update request DTO
/// </summary>
public class StockUpdateRequest
{
public int Quantity { get; set; }
}}
Repository Pattern Benefits
✅ Separation of Concerns : Data access logic separated from business logic
✅ Testability : Easy to mock repositories for unit testing
✅ Flexibility : Easy to change data access technology
✅ Maintainability : Centralized data access logic
✅ Reusability : Generic repository can be used across entities
3. Unit of Work Pattern: Transaction Management
The Problem: Inconsistent Data Operations
Without a Unit of Work, managing transactions across multiple repositories becomes challenging:
// ❌ Problem: Manual transaction management across repositoriespublic class OrderService{
private readonly IProductRepository _productRepository;
private readonly IOrderRepository _orderRepository;
private readonly ApplicationDbContext _context;
public async Task<bool> PlaceOrder(Order order)
{
using var transaction = await _context.Database.BeginTransactionAsync();
try
{
// Update product stock
foreach (var item in order.Items)
{
var product = await _productRepository.GetByIdAsync(item.ProductId);
product.StockQuantity -= item.Quantity;
await _productRepository.UpdateAsync(product);
}
// Create order
await _orderRepository.AddAsync(order);
await transaction.CommitAsync();
return true;
}
catch
{
await transaction.RollbackAsync();
throw;
}
}}
Unit of Work Solution
The Unit of Work pattern maintains a list of objects affected by a business transaction and coordinates writing out changes and resolving concurrency problems.
Step 1: Unit of Work Interface
// Interfaces/IUnitOfWork.csnamespace ECommercePatterns.Interfaces{
/// <summary>
/// Unit of Work interface for transaction management
/// </summary>
public interface IUnitOfWork : IDisposable
{
IProductRepository Products { get; }
ICategoryRepository Categories { get; }
IOrderRepository Orders { get; }
IUserRepository Users { get; }
Task<int> SaveChangesAsync(CancellationToken cancellationToken = default);
Task BeginTransactionAsync();
Task CommitTransactionAsync();
Task RollbackTransactionAsync();
Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default);
}
/// <summary>
/// Category repository interface
/// </summary>
public interface ICategoryRepository : IExtendedRepository<Category>
{
Task<IEnumerable<Category>> GetActiveCategoriesAsync();
Task<Category?> GetCategoryWithProductsAsync(int categoryId);
}
/// <summary>
/// Order repository interface
/// </summary>
public interface IOrderRepository : IExtendedRepository<Order>
{
Task<IEnumerable<Order>> GetOrdersByUserAsync(int userId);
Task<Order?> GetOrderWithItemsAsync(int orderId);
Task UpdateOrderStatusAsync(int orderId, OrderStatus status);
}
/// <summary>
/// User repository interface
/// </summary>
public interface IUserRepository : IExtendedRepository<User>
{
Task<User?> GetUserByEmailAsync(string email);
Task<bool> UserExistsAsync(string email);
}}
Step 2: Unit of Work Implementation.
// Repositories/UnitOfWork.csusing Microsoft.EntityFrameworkCore.Storage;
namespace ECommercePatterns.Repositories{
/// <summary>
/// Unit of Work implementation coordinating multiple repositories
/// </summary>
public class UnitOfWork : IUnitOfWork
{
private readonly ECommerceContext _context;
private IDbContextTransaction? _transaction;
public UnitOfWork(ECommerceContext context)
{
_context = context;
Products = new ProductRepository(context);
Categories = new CategoryRepository(context);
Orders = new OrderRepository(context);
Users = new UserRepository(context);
}
public IProductRepository Products { get; }
public ICategoryRepository Categories { get; }
public IOrderRepository Orders { get; }
public IUserRepository Users { get; }
public async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default)
{
return await _context.SaveChangesAsync(cancellationToken);
}
public async Task BeginTransactionAsync()
{
_transaction = await _context.Database.BeginTransactionAsync();
}
public async Task CommitTransactionAsync()
{
if (_transaction == null)
{
throw new InvalidOperationException("Transaction not started");
}
try
{
await SaveChangesAsync();
await _transaction.CommitAsync();
}
finally
{
await _transaction.DisposeAsync();
_transaction = null;
}
}
public async Task RollbackTransactionAsync()
{
if (_transaction == null)
{
throw new InvalidOperationException("Transaction not started");
}
await _transaction.RollbackAsync();
await _transaction.DisposeAsync();
_transaction = null;
}
public async Task<bool> SaveEntitiesAsync(CancellationToken cancellationToken = default)
{
try
{
await SaveChangesAsync(cancellationToken);
return true;
}
catch (Exception ex)
{
// Log exception
return false;
}
}
public void Dispose()
{
_transaction?.Dispose();
_context.Dispose();
}
}}
Step 3: Additional Repository Implementations.
// Repositories/CategoryRepository.csusing Microsoft.EntityFrameworkCore;
namespace ECommercePatterns.Repositories{
public class CategoryRepository : ExtendedRepository<Category>, ICategoryRepository
{
public CategoryRepository(ECommerceContext context) : base(context)
{
}
public async Task<IEnumerable<Category>> GetActiveCategoriesAsync()
{
return await _context.Categories
.Where(c => c.IsActive)
.OrderBy(c => c.Name)
.ToListAsync();
}
public async Task<Category?> GetCategoryWithProductsAsync(int categoryId)
{
return await _context.Categories
.Include(c => c.Products.Where(p => p.IsActive))
.FirstOrDefaultAsync(c => c.Id == categoryId && c.IsActive);
}
}}
// Repositories/OrderRepository.csusing Microsoft.EntityFrameworkCore;
namespace ECommercePatterns.Repositories{
public class OrderRepository : ExtendedRepository<Order>, IOrderRepository
{
public OrderRepository(ECommerceContext context) : base(context)
{
}
public async Task<IEnumerable<Order>> GetOrdersByUserAsync(int userId)
{
return await _context.Orders
.Include(o => o.Items)
.ThenInclude(i => i.Product)
.Where(o => o.UserId == userId)
.OrderByDescending(o => o.CreatedAt)
.ToListAsync();
}
public async Task<Order?> GetOrderWithItemsAsync(int orderId)
{
return await _context.Orders
.Include(o => o.Items)
.ThenInclude(i => i.Product)
.FirstOrDefaultAsync(o => o.Id == orderId);
}
public async Task UpdateOrderStatusAsync(int orderId, OrderStatus status)
{
var order = await _context.Orders.FindAsync(orderId);
if (order != null)
{
order.Status = status;
order.UpdatedAt = DateTime.UtcNow;
await _context.SaveChangesAsync();
}
}
}}
Step 4: Service Using Unit of Work.
// Services/OrderService.csnamespace ECommercePatterns.Services{
/// <summary>
/// Order service using Unit of Work pattern for transaction management
/// </summary>
public interface IOrderService
{
Task<OrderResult> PlaceOrderAsync(CreateOrderRequest request);
Task<bool> CancelOrderAsync(int orderId);
Task<Order?> GetOrderDetailsAsync(int orderId);
}
public class OrderService : IOrderService
{
private readonly IUnitOfWork _unitOfWork;
private readonly ILogger<OrderService> _logger;
public OrderService(IUnitOfWork unitOfWork, ILogger<OrderService> logger)
{
_unitOfWork = unitOfWork;
_logger = logger;
}
public async Task<OrderResult> PlaceOrderAsync(CreateOrderRequest request)
{
await _unitOfWork.BeginTransactionAsync();
try
{
_logger.LogInformation("Placing order for user {UserId}", request.UserId);
// Validate products and stock
var validationResult = await ValidateOrderItemsAsync(request.Items);
if (!validationResult.IsValid)
{
return OrderResult.Failure(validationResult.Errors);
}
// Create order
var order = new Order
{
UserId = request.UserId,
Status = OrderStatus.Pending,
TotalAmount = await CalculateOrderTotalAsync(request.Items),
ShippingAddress = request.ShippingAddress,
Items = request.Items.Select(item => new OrderItem
{
ProductId = item.ProductId,
Quantity = item.Quantity,
UnitPrice = await GetProductPriceAsync(item.ProductId)
}).ToList()
};
// Update product stock
foreach (var item in request.Items)
{
await _unitOfWork.Products.UpdateStockAsync(item.ProductId, -item.Quantity);
}
// Save order
await _unitOfWork.Orders.AddAsync(order);
await _unitOfWork.CommitTransactionAsync();
_logger.LogInformation("Order {OrderId} placed successfully", order.Id);
return OrderResult.Success(order);
}
catch (Exception ex)
{
await _unitOfWork.RollbackTransactionAsync();
_logger.LogError(ex, "Error placing order for user {UserId}", request.UserId);
return OrderResult.Failure(new[] { "An error occurred while placing the order" });
}
}
public async Task<bool> CancelOrderAsync(int orderId)
{
await _unitOfWork.BeginTransactionAsync();
try
{
var order = await _unitOfWork.Orders.GetOrderWithItemsAsync(orderId);
if (order == null || order.Status != OrderStatus.Pending)
{
return false;
}
// Restore product stock
foreach (var item in order.Items)
{
await _unitOfWork.Products.UpdateStockAsync(item.ProductId, item.Quantity);
}
// Update order status
await _unitOfWork.Orders.UpdateOrderStatusAsync(orderId, OrderStatus.Cancelled);
await _unitOfWork.CommitTransactionAsync();
_logger.LogInformation("Order {OrderId} cancelled successfully", orderId);
return true;
}
catch (Exception ex)
{
await _unitOfWork.RollbackTransactionAsync();
_logger.LogError(ex, "Error cancelling order {OrderId}", orderId);
return false;
}
}
public async Task<Order?> GetOrderDetailsAsync(int orderId)
{
return await _unitOfWork.Orders.GetOrderWithItemsAsync(orderId);
}
private async Task<ValidationResult> ValidateOrderItemsAsync(List<OrderItemRequest> items)
{
var errors = new List<string>();
foreach (var item in items)
{
var product = await _unitOfWork.Products.GetByIdAsync(item.ProductId);
if (product == null)
{
errors.Add($"Product with ID {item.ProductId} not found");
}
else if (!product.IsActive)
{
errors.Add($"Product {product.Name} is not available");
}
else if (product.StockQuantity < item.Quantity)
{
errors.Add($"Insufficient stock for {product.Name}. Available: {product.StockQuantity}");
}
}
return new ValidationResult(errors);
}
private async Task<decimal> CalculateOrderTotalAsync(List<OrderItemRequest> items)
{
decimal total = 0;
foreach (var item in items)
{
var price = await GetProductPriceAsync(item.ProductId);
total += price * item.Quantity;
}
return total;
}
private async Task<decimal> GetProductPriceAsync(int productId)
{
var product = await _unitOfWork.Products.GetByIdAsync(productId);
return product?.Price ?? 0;
}
}
/// <summary>
/// Order operation result
/// </summary>
public class OrderResult
{
public bool Success { get; }
public Order? Order { get; }
public IEnumerable<string> Errors { get; }
private OrderResult(bool success, Order? order, IEnumerable<string> errors)
{
Success = success;
Order = order;
Errors = errors;
}
public static OrderResult Success(Order order) => new OrderResult(true, order, Array.Empty<string>());
public static OrderResult Failure(IEnumerable<string> errors) => new OrderResult(false, null, errors);
}
/// <summary>
/// Validation result for order items
/// </summary>
public class ValidationResult
{
public bool IsValid => !Errors.Any();
public List<string> Errors { get; }
public ValidationResult(List<string> errors)
{
Errors = errors;
}
}}
4. Singleton Pattern: Shared Instance Management
The Problem: Uncontrolled Instance Creation
Without proper singleton management, you might create multiple instances unnecessarily:
// ❌ Problem: Multiple instances causing resource wastepublic class CacheService{
private readonly Dictionary<string, object> _cache = new();
public void Set(string key, object value) => _cache[key] = value;
public object Get(string key) => _cache.GetValueOrDefault(key);}
// Multiple instances createdvar cache1 = new CacheService();var cache2 = new CacheService();// cache1 and cache2 have different data - inconsistent!
Singleton Pattern Solutions
Approach 1: ASP.NET Core Built-in Singleton
// Services/ICacheService.csnamespace ECommercePatterns.Services{
/// <summary>
/// Cache service interface for application-level caching
/// </summary>
public interface ICacheService
{
Task<T?> GetAsync<T>(string key);
Task SetAsync<T>(string key, T value, TimeSpan? expiration = null);
Task RemoveAsync(string key);
Task<bool> ExistsAsync(string key);
Task ClearAsync();
}
/// <summary>
/// In-memory cache service implementation as singleton
/// </summary>
public class MemoryCacheService : ICacheService
{
private readonly ConcurrentDictionary<string, CacheEntry> _cache = new();
private readonly ILogger<MemoryCacheService> _logger;
public MemoryCacheService(ILogger<MemoryCacheService> logger)
{
_logger = logger;
_logger.LogInformation("MemoryCacheService initialized");
}
public Task<T?> GetAsync<T>(string key)
{
if (_cache.TryGetValue(key, out var entry) && !IsExpired(entry))
{
_logger.LogDebug("Cache hit for key: {Key}", key);
return Task.FromResult((T?)entry.Value);
}
_logger.LogDebug("Cache miss for key: {Key}", key);
return Task.FromResult(default(T));
}
public Task SetAsync<T>(string key, T value, TimeSpan? expiration = null)
{
var entry = new CacheEntry
{
Value = value,
Expiration = expiration.HasValue ? DateTime.UtcNow.Add(expiration.Value) : null
};
_cache.AddOrUpdate(key, entry, (k, old) => entry);
_logger.LogDebug("Cache set for key: {Key} with expiration: {Expiration}", key, expiration);
return Task.CompletedTask;
}
public Task RemoveAsync(string key)
{
_cache.TryRemove(key, out _);
_logger.LogDebug("Cache removed for key: {Key}", key);
return Task.CompletedTask;
}
public Task<bool> ExistsAsync(string key)
{
var exists = _cache.TryGetValue(key, out var entry) && !IsExpired(entry);
return Task.FromResult(exists);
}
public Task ClearAsync()
{
_cache.Clear();
_logger.LogInformation("Cache cleared");
return Task.CompletedTask;
}
private bool IsExpired(CacheEntry entry)
{
return entry.Expiration.HasValue && entry.Expiration.Value < DateTime.UtcNow;
}
// Background cleanup of expired entries
public void CleanupExpiredEntries()
{
var expiredKeys = _cache.Where(kvp => IsExpired(kvp.Value))
.Select(kvp => kvp.Key)
.ToList();
foreach (var key in expiredKeys)
{
_cache.TryRemove(key, out _);
}
if (expiredKeys.Count > 0)
{
_logger.LogInformation("Cleaned up {Count} expired cache entries", expiredKeys.Count);
}
}
private class CacheEntry
{
public object? Value { get; set; }
public DateTime? Expiration { get; set; }
}
}}
Approach 2: Configuration Singleton
// Services/AppConfigService.csnamespace ECommercePatterns.Services{
/// <summary>
/// Application configuration service with singleton behavior
/// </summary>
public interface IAppConfigService
{
string GetSetting(string key);
T GetSetting<T>(string key, T defaultValue = default!);
void UpdateSetting(string key, string value);
IReadOnlyDictionary<string, string> GetAllSettings();
}
public class AppConfigService : IAppConfigService
{
private readonly ConcurrentDictionary<string, string> _settings;
private readonly IConfiguration _configuration;
private readonly ILogger<AppConfigService> _logger;
// Static instance for true singleton (use carefully!)
private static AppConfigService? _instance;
private static readonly object _lockObject = new object();
public AppConfigService(IConfiguration configuration, ILogger<AppConfigService> logger)
{
_configuration = configuration;
_logger = logger;
_settings = LoadSettingsFromConfig();
// Singleton instance management
lock (_lockObject)
{
if (_instance == null)
{
_instance = this;
}
}
_logger.LogInformation("AppConfigService initialized with {Count} settings", _settings.Count);
}
public static AppConfigService? Instance => _instance;
public string GetSetting(string key)
{
if (_settings.TryGetValue(key, out var value))
{
return value;
}
// Fallback to configuration
var configValue = _configuration[key];
if (!string.IsNullOrEmpty(configValue))
{
_settings[key] = configValue;
return configValue;
}
throw new KeyNotFoundException($"Setting '{key}' not found");
}
public T GetSetting<T>(string key, T defaultValue = default!)
{
try
{
var value = GetSetting(key);
return (T)Convert.ChangeType(value, typeof(T));
}
catch
{
return defaultValue;
}
}
public void UpdateSetting(string key, string value)
{
_settings.AddOrUpdate(key, value, (k, old) => value);
_logger.LogInformation("Setting updated: {Key} = {Value}", key, value);
}
public IReadOnlyDictionary<string, string> GetAllSettings()
{
return new ReadOnlyDictionary<string, string>(_settings);
}
private ConcurrentDictionary<string, string> LoadSettingsFromConfig()
{
var settings = new ConcurrentDictionary<string, string>();
// Load from appsettings.json
foreach (var setting in _configuration.AsEnumerable())
{
if (!string.IsNullOrEmpty(setting.Value))
{
settings[setting.Key] = setting.Value;
}
}
return settings;
}
}}
Approach 3: Lazy Singleton with Dependency Injection.
// Services/GlobalStatisticsService.csnamespace ECommercePatterns.Services{
/// <summary>
/// Global application statistics service using lazy singleton pattern
/// </summary>
public interface IGlobalStatisticsService
{
Task<AppStatistics> GetStatisticsAsync();
Task IncrementRequestCountAsync();
Task RecordErrorAsync(string errorType);
Task RecordOrderAsync(decimal amount);
}
public class GlobalStatisticsService : IGlobalStatisticsService
{
private readonly AppStatistics _statistics = new();
private readonly SemaphoreSlim _lock = new SemaphoreSlim(1, 1);
private readonly ILogger<GlobalStatisticsService> _logger;
// Lazy singleton instance
private static readonly Lazy<GlobalStatisticsService> _instance =
new Lazy<GlobalStatisticsService>(() => new GlobalStatisticsService());
public static GlobalStatisticsService Instance => _instance.Value;
private GlobalStatisticsService()
{
_logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger<GlobalStatisticsService>();
_logger.LogInformation("GlobalStatisticsService singleton initialized");
}
public async Task<AppStatistics> GetStatisticsAsync()
{
await _lock.WaitAsync();
try
{
return _statistics.Clone();
}
finally
{
_lock.Release();
}
}
public async Task IncrementRequestCountAsync()
{
await _lock.WaitAsync();
try
{
_statistics.TotalRequests++;
_statistics.LastUpdated = DateTime.UtcNow;
_logger.LogDebug("Request count incremented to {Count}", _statistics.TotalRequests);
}
finally
{
_lock.Release();
}
}
public async Task RecordErrorAsync(string errorType)
{
await _lock.WaitAsync();
try
{
_statistics.TotalErrors++;
if (_statistics.ErrorCounts.ContainsKey(errorType))
{
_statistics.ErrorCounts[errorType]++;
}
else
{
_statistics.ErrorCounts[errorType] = 1;
}
_statistics.LastUpdated = DateTime.UtcNow;
_logger.LogWarning("Error recorded: {ErrorType}. Total errors: {TotalErrors}",
errorType, _statistics.TotalErrors);
}
finally
{
_lock.Release();
}
}
public async Task RecordOrderAsync(decimal amount)
{
await _lock.WaitAsync();
try
{
_statistics.TotalOrders++;
_statistics.TotalRevenue += amount;
_statistics.LastUpdated = DateTime.UtcNow;
_logger.LogInformation("Order recorded: Amount {Amount}. Total revenue: {TotalRevenue}",
amount, _statistics.TotalRevenue);
}
finally
{
_lock.Release();
}
}
}
/// <summary>
/// Application statistics data model
/// </summary>
public class AppStatistics
{
public long TotalRequests { get; set; }
public long TotalOrders { get; set; }
public long TotalErrors { get; set; }
public decimal TotalRevenue { get; set; }
public DateTime LastUpdated { get; set; }
public Dictionary<string, int> ErrorCounts { get; set; } = new();
public AppStatistics Clone()
{
return new AppStatistics
{
TotalRequests = TotalRequests,
TotalOrders = TotalOrders,
TotalErrors = TotalErrors,
TotalRevenue = TotalRevenue,
LastUpdated = LastUpdated,
ErrorCounts = new Dictionary<string, int>(ErrorCounts)
};
}
}}
Dependency Injection Registration
// Program.cs - Singleton Registration
builder.Services.AddSingleton<ICacheService, MemoryCacheService>();
builder.Services.AddSingleton<IAppConfigService, AppConfigService>();
builder.Services.AddSingleton<IGlobalStatisticsService, GlobalStatisticsService>();
// Background service for cache cleanup
builder.Services.AddHostedService<CacheCleanupService>();
// Services/CacheCleanupService.csnamespace ECommercePatterns.Services{
/// <summary>
/// Background service for cache maintenance
/// </summary>
public class CacheCleanupService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<CacheCleanupService> _logger;
private readonly TimeSpan _cleanupInterval = TimeSpan.FromMinutes(30);
public CacheCleanupService(IServiceProvider serviceProvider, ILogger<CacheCleanupService> logger)
{
_serviceProvider = serviceProvider;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("Cache cleanup service started");
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = _serviceProvider.CreateScope();
var cacheService = scope.ServiceProvider.GetRequiredService<ICacheService>() as MemoryCacheService;
cacheService?.CleanupExpiredEntries();
_logger.LogDebug("Cache cleanup completed");
}
catch (Exception ex)
{
_logger.LogError(ex, "Error during cache cleanup");
}
await Task.Delay(_cleanupInterval, stoppingToken);
}
}
}}
5. Factory Pattern: Object Creation Magic
The Problem: Complex Object Creation Logic
Without the Factory pattern, object creation logic spreads throughout the application:
// ❌ Problem: Complex object creation scattered everywherepublic class PaymentProcessor{
public IPaymentMethod CreatePaymentMethod(string type, PaymentInfo info)
{
switch (type.ToLower())
{
case "creditcard":
return new CreditCardPayment
{
CardNumber = info.CardNumber,
ExpiryDate = info.ExpiryDate,
CVV = info.CVV
};
case "paypal":
return new PayPalPayment
{
Email = info.Email,
TransactionId = info.TransactionId
};
case "crypto":
return new CryptoPayment
{
WalletAddress = info.WalletAddress,
Currency = info.Currency
};
default:
throw new ArgumentException($"Unknown payment type: {type}");
}
}}
// Same switch statements repeated in multiple places// Hard to maintain and extend
Factory Pattern Solutions
Approach 1: Simple Factory Pattern
// Patterns/Factories/IPaymentMethod.csnamespace ECommercePatterns.Patterns.Factories{
/// <summary>
/// Payment method interface
/// </summary>
public interface IPaymentMethod
{
string Type { get; }
Task<PaymentResult> ProcessPaymentAsync(decimal amount);
bool Validate();
}
/// <summary>
/// Payment information DTO
/// </summary>
public class PaymentInfo
{
public string? CardNumber { get; set; }
public string? ExpiryDate { get; set; }
public string? CVV { get; set; }
public string? Email { get; set; }
public string? TransactionId { get; set; }
public string? WalletAddress { get; set; }
public string? Currency { get; set; }
}
/// <summary>
/// Payment result
/// </summary>
public class PaymentResult
{
public bool Success { get; set; }
public string TransactionId { get; set; } = string.Empty;
public string Message { get; set; } = string.Empty;
public DateTime ProcessedAt { get; set; } = DateTime.UtcNow;
}
/// <summary>
/// Simple payment factory
/// </summary>
public interface IPaymentFactory
{
IPaymentMethod CreatePaymentMethod(string type, PaymentInfo paymentInfo);
IEnumerable<string> GetAvailablePaymentMethods();
}
public class PaymentFactory : IPaymentFactory
{
private readonly ILogger<PaymentFactory> _logger;
public PaymentFactory(ILogger<PaymentFactory> logger)
{
_logger = logger;
}
public IPaymentMethod CreatePaymentMethod(string type, PaymentInfo paymentInfo)
{
_logger.LogInformation("Creating payment method of type: {Type}", type);
return type.ToLower() switch
{
"creditcard" => new CreditCardPayment(paymentInfo),
"paypal" => new PayPalPayment(paymentInfo),
"crypto" => new CryptoPayment(paymentInfo),
"applepay" => new ApplePayPayment(paymentInfo),
_ => throw new ArgumentException($"Unsupported payment type: {type}")
};
}
public IEnumerable<string> GetAvailablePaymentMethods()
{
return new[] { "creditcard", "paypal", "crypto", "applepay" };
}
}}
Approach 2: Abstract Factory Pattern
// Patterns/Factories/AbstractFactory.csnamespace ECommercePatterns.Patterns.Factories{
/// <summary>
/// Abstract factory for creating payment processors
/// </summary>
public interface IPaymentProcessorFactory
{
IPaymentProcessor CreateProcessor(string countryCode);
IRefundProcessor CreateRefundProcessor(string countryCode);
}
/// <summary>
/// Payment processor interface
/// </summary>
public interface IPaymentProcessor
{
Task<PaymentResult> ProcessAsync(decimal amount, IPaymentMethod paymentMethod);
Task<bool> ValidateAsync(IPaymentMethod paymentMethod);
}
/// <summary>
/// Refund processor interface
/// </summary>
public interface IRefundProcessor
{
Task<RefundResult> ProcessRefundAsync(string transactionId, decimal amount);
}
/// <summary>
/// Concrete factory for US payment systems
/// </summary>
public class USPaymentProcessorFactory : IPaymentProcessorFactory
{
private readonly ILogger<USPaymentProcessorFactory> _logger;
public USPaymentProcessorFactory(ILogger<USPaymentProcessorFactory> logger)
{
_logger = logger;
}
public IPaymentProcessor CreateProcessor(string countryCode)
{
_logger.LogInformation("Creating US payment processor for country: {Country}", countryCode);
return new USPaymentProcessor();
}
public IRefundProcessor CreateRefundProcessor(string countryCode)
{
_logger.LogInformation("Creating US refund processor for country: {Country}", countryCode);
return new USRefundProcessor();
}
}
/// <summary>
/// Concrete factory for EU payment systems
/// </summary>
public class EUPaymentProcessorFactory : IPaymentProcessorFactory
{
private readonly ILogger<EUPaymentProcessorFactory> _logger;
public EUPaymentProcessorFactory(ILogger<EUPaymentProcessorFactory> logger)
{
_logger = logger;
}
public IPaymentProcessor CreateProcessor(string countryCode)
{
_logger.LogInformation("Creating EU payment processor for country: {Country}", countryCode);
return new EUPaymentProcessor();
}
public IRefundProcessor CreateRefundProcessor(string countryCode)
{
_logger.LogInformation("Creating EU refund processor for country: {Country}", countryCode);
return new EURefundProcessor();
}
}}
Approach 3: Factory Method Pattern
// Patterns/Factories/FactoryMethod.csnamespace ECommercePatterns.Patterns.Factories{
/// <summary>
/// Base creator class with factory method
/// </summary>
public abstract class ReportGenerator
{
protected readonly ILogger<ReportGenerator> _logger;
protected ReportGenerator(ILogger<ReportGenerator> logger)
{
_logger = logger;
}
// Factory method
public abstract IReport CreateReport();
// Business logic that uses the factory method
public async Task<ReportResult> GenerateReportAsync()
{
_logger.LogInformation("Starting report generation");
var report = CreateReport();
var result = await report.GenerateAsync();
_logger.LogInformation("Report generation completed: {Success}", result.Success);
return result;
}
}
/// <summary>
/// Concrete creator for sales reports
/// </summary>
public class SalesReportGenerator : ReportGenerator
{
public SalesReportGenerator(ILogger<SalesReportGenerator> logger) : base(logger)
{
}
public override IReport CreateReport()
{
_logger.LogDebug("Creating sales report");
return new SalesReport();
}
}
/// <summary>
/// Concrete creator for inventory reports
/// </summary>
public class InventoryReportGenerator : ReportGenerator
{
public InventoryReportGenerator(ILogger<InventoryReportGenerator> logger) : base(logger)
{
}
public override IReport CreateReport()
{
_logger.LogDebug("Creating inventory report");
return new InventoryReport();
}
}
/// <summary>
/// Report interface
/// </summary>
public interface IReport
{
string ReportType { get; }
Task<ReportResult> GenerateAsync();
}
/// <summary>
/// Sales report implementation
/// </summary>
public class SalesReport : IReport
{
public string ReportType => "Sales";
public async Task<ReportResult> GenerateAsync()
{
// Simulate report generation
await Task.Delay(1000);
return new ReportResult
{
Success = true,
ReportData = "Sales report data...",
GeneratedAt = DateTime.UtcNow
};
}
}
/// <summary>
/// Inventory report implementation
/// </summary>
public class InventoryReport : IReport
{
public string ReportType => "Inventory";
public async Task<ReportResult> GenerateAsync()
{
// Simulate report generation
await Task.Delay(1500);
return new ReportResult
{
Success = true,
ReportData = "Inventory report data...",
GeneratedAt = DateTime.UtcNow
};
}
}
/// <summary>
/// Report generation result
/// </summary>
public class ReportResult
{
public bool Success { get; set; }
public string ReportData { get; set; } = string.Empty;
public DateTime GeneratedAt { get; set; }
public string? ErrorMessage { get; set; }
}}
Concrete Payment Implementations
// Patterns/Factories/PaymentImplementations.csnamespace ECommercePatterns.Patterns.Factories{
/// <summary>
/// Credit card payment implementation
/// </summary>
public class CreditCardPayment : IPaymentMethod
{
private readonly PaymentInfo _paymentInfo;
public string Type => "CreditCard";
public CreditCardPayment(PaymentInfo paymentInfo)
{
_paymentInfo = paymentInfo;
}
public async Task<PaymentResult> ProcessPaymentAsync(decimal amount)
{
// Simulate payment processing
await Task.Delay(500);
if (string.IsNullOrEmpty(_paymentInfo.CardNumber) ||
string.IsNullOrEmpty(_paymentInfo.ExpiryDate))
{
return new PaymentResult
{
Success = false,
Message = "Invalid credit card information"
};
}
// Simulate successful payment
return new PaymentResult
{
Success = true,
TransactionId = Guid.NewGuid().ToString(),
Message = "Credit card payment processed successfully"
};
}
public bool Validate()
{
return !string.IsNullOrEmpty(_paymentInfo.CardNumber) &&
!string.IsNullOrEmpty(_paymentInfo.ExpiryDate) &&
!string.IsNullOrEmpty(_paymentInfo.CVV) &&
_paymentInfo.CardNumber.Length == 16 &&
_paymentInfo.CVV.Length == 3;
}
}
/// <summary>
/// PayPal payment implementation
/// </summary>
public class PayPalPayment : IPaymentMethod
{
private readonly PaymentInfo _paymentInfo;
public string Type => "PayPal";
public PayPalPayment(PaymentInfo paymentInfo)
{
_paymentInfo = paymentInfo;
}
public async Task<PaymentResult> ProcessPaymentAsync(decimal amount)
{
// Simulate PayPal payment processing
await Task.Delay(800);
if (string.IsNullOrEmpty(_paymentInfo.Email))
{
return new PaymentResult
{
Success = false,
Message = "Invalid PayPal email"
};
}
// Simulate successful payment
return new PaymentResult
{
Success = true,
TransactionId = Guid.NewGuid().ToString(),
Message = "PayPal payment processed successfully"
};
}
public bool Validate()
{
return !string.IsNullOrEmpty(_paymentInfo.Email) &&
_paymentInfo.Email.Contains('@');
}
}
/// <summary>
/// US payment processor implementation
/// </summary>
public class USPaymentProcessor : IPaymentProcessor
{
public async Task<PaymentResult> ProcessAsync(decimal amount, IPaymentMethod paymentMethod)
{
// US-specific payment processing logic
await Task.Delay(300);
if (amount > 10000)
{
return new PaymentResult
{
Success = false,
Message = "Amount exceeds US regulatory limit"
};
}
return await paymentMethod.ProcessPaymentAsync(amount);
}
public async Task<bool> ValidateAsync(IPaymentMethod paymentMethod)
{
await Task.Delay(100);
return paymentMethod.Validate();
}
}}
Factory Pattern Usage in Controllers
// Controllers/PaymentsController.csusing ECommercePatterns.Patterns.Factories;
namespace ECommercePatterns.Controllers{
/// <summary>
/// Payments controller demonstrating factory pattern usage
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class PaymentsController : ControllerBase
{
private readonly IPaymentFactory _paymentFactory;
private readonly IPaymentProcessorFactory _processorFactory;
private readonly ILogger<PaymentsController> _logger;
public PaymentsController(
IPaymentFactory paymentFactory,
IPaymentProcessorFactory processorFactory,
ILogger<PaymentsController> logger)
{
_paymentFactory = paymentFactory;
_processorFactory = processorFactory;
_logger = logger;
}
[HttpPost]
public async Task<ActionResult<PaymentResult>> ProcessPayment([FromBody] ProcessPaymentRequest request)
{
try
{
_logger.LogInformation("Processing payment of {Amount} via {Method}",
request.Amount, request.PaymentMethod);
// Create payment method using factory
var paymentMethod = _paymentFactory.CreatePaymentMethod(
request.PaymentMethod, request.PaymentInfo);
// Validate payment method
if (!paymentMethod.Validate())
{
return BadRequest("Invalid payment information");
}
// Create appropriate processor based on country
var processor = _processorFactory.CreateProcessor(request.CountryCode);
// Process payment
var result = await processor.ProcessAsync(request.Amount, paymentMethod);
if (result.Success)
{
_logger.LogInformation("Payment processed successfully. Transaction: {TransactionId}",
result.TransactionId);
return Ok(result);
}
else
{
_logger.LogWarning("Payment processing failed: {Message}", result.Message);
return BadRequest(result);
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error processing payment");
return StatusCode(500, "An error occurred while processing payment");
}
}
[HttpGet("methods")]
public ActionResult<IEnumerable<string>> GetAvailablePaymentMethods()
{
var methods = _paymentFactory.GetAvailablePaymentMethods();
return Ok(methods);
}
}
/// <summary>
/// Payment processing request
/// </summary>
public class ProcessPaymentRequest
{
public decimal Amount { get; set; }
public string PaymentMethod { get; set; } = string.Empty;
public string CountryCode { get; set; } = "US";
public PaymentInfo PaymentInfo { get; set; } = new();
}}
6. Strategy Pattern: Algorithmic Flexibility
The Problem: Complex Conditional Logic
Without the Strategy pattern, you end up with complex conditional statements:
// ❌ Problem: Complex conditional logic for different algorithmspublic class ShippingCalculator{
public decimal CalculateShipping(string method, decimal weight, decimal distance)
{
if (method == "standard")
{
return weight * 0.5m + distance * 0.1m;
}
else if (method == "express")
{
return weight * 1.2m + distance * 0.3m + 10m;
}
else if (method == "overnight")
{
return weight * 2.0m + distance * 0.5m + 25m;
}
else if (method == "international")
{
return (weight * 3.0m + distance * 0.8m) * 1.1m; // 10% international fee
}
else
{
throw new ArgumentException($"Unknown shipping method: {method}");
}
}}
Strategy Pattern Solution
The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable.
Step 1: Define Strategy Interface
// Patterns/Strategies/IShippingStrategy.csnamespace ECommercePatterns.Patterns.Strategies{
/// <summary>
/// Shipping strategy interface
/// </summary>
public interface IShippingStrategy
{
string Name { get; }
decimal CalculateCost(decimal weight, decimal distance, string destination);
TimeSpan EstimateDelivery(decimal distance);
bool IsAvailable(string destination);
}
/// <summary>
/// Shipping calculation context
/// </summary>
public class ShippingContext
{
public decimal Weight { get; set; }
public decimal Distance { get; set; }
public string Destination { get; set; } = string.Empty;
public DateTime OrderDate { get; set; } = DateTime.UtcNow;
}
/// <summary>
/// Shipping calculation result
/// </summary>
public class ShippingResult
{
public decimal Cost { get; set; }
public TimeSpan EstimatedDelivery { get; set; }
public string Method { get; set; } = string.Empty;
public bool IsAvailable { get; set; }
public string? Message { get; set; }
}}
Step 2: Implement Concrete Strategies
// Patterns/Strategies/ShippingStrategies.csnamespace ECommercePatterns.Patterns.Strategies{
/// <summary>
/// Standard shipping strategy
/// </summary>
public class StandardShippingStrategy : IShippingStrategy
{
public string Name => "Standard";
public decimal CalculateCost(decimal weight, decimal distance, string destination)
{
var baseCost = weight * 0.5m + distance * 0.1m;
// Additional charges for remote destinations
if (IsRemoteDestination(destination))
{
baseCost *= 1.2m;
}
return Math.Round(baseCost, 2);
}
public TimeSpan EstimateDelivery(decimal distance)
{
var days = (int)Math.Ceiling(distance / 100); // 100 km per day
return TimeSpan.FromDays(Math.Max(days, 3)); // Minimum 3 days
}
public bool IsAvailable(string destination)
{
return !IsRestrictedDestination(destination);
}
private bool IsRemoteDestination(string destination)
{
var remoteDestinations = new[] { "hawaii", "alaska", "puerto rico" };
return remoteDestinations.Contains(destination.ToLower());
}
private bool IsRestrictedDestination(string destination)
{
var restrictedDestinations = new[] { "cuba", "north korea", "syria" };
return restrictedDestinations.Contains(destination.ToLower());
}
}
/// <summary>
/// Express shipping strategy
/// </summary>
public class ExpressShippingStrategy : IShippingStrategy
{
public string Name => "Express";
public decimal CalculateCost(decimal weight, decimal distance, string destination)
{
var baseCost = weight * 1.2m + distance * 0.3m + 10m; // Base + premium
// Weekend surcharge
if (IsWeekend(DateTime.UtcNow))
{
baseCost += 5m;
}
return Math.Round(baseCost, 2);
}
public TimeSpan EstimateDelivery(decimal distance)
{
var days = (int)Math.Ceiling(distance / 300); // 300 km per day
return TimeSpan.FromDays(Math.Max(days, 2)); // Minimum 2 days
}
public bool IsAvailable(string destination)
{
return !IsRestrictedDestination(destination) &&
!IsRemoteDestination(destination);
}
private bool IsWeekend(DateTime date)
{
return date.DayOfWeek == DayOfWeek.Saturday ||
date.DayOfWeek == DayOfWeek.Sunday;
}
private bool IsRemoteDestination(string destination)
{
var remoteDestinations = new[] { "hawaii", "alaska" };
return remoteDestinations.Contains(destination.ToLower());
}
private bool IsRestrictedDestination(string destination)
{
var restrictedDestinations = new[] { "cuba", "north korea" };
return restrictedDestinations.Contains(destination.ToLower());
}
}
/// <summary>
/// Overnight shipping strategy
/// </summary>
public class OvernightShippingStrategy : IShippingStrategy
{
public string Name => "Overnight";
public decimal CalculateCost(decimal weight, decimal distance, string destination)
{
var baseCost = weight * 2.0m + distance * 0.5m + 25m;
// Urgency premium
if (IsAfterHours(DateTime.UtcNow))
{
baseCost *= 1.5m;
}
return Math.Round(baseCost, 2);
}
public TimeSpan EstimateDelivery(decimal distance)
{
var hours = (int)Math.Ceiling(distance / 50); // 50 km per hour (by air)
return TimeSpan.FromHours(Math.Max(hours, 24)); // Minimum 24 hours
}
public bool IsAvailable(string destination)
{
return !IsRestrictedDestination(destination) &&
distance <= 5000 && // Maximum distance
IsServiceAvailableToday();
}
private bool IsAfterHours(DateTime date)
{
return date.Hour < 8 || date.Hour >= 18; // 6 PM to 8 AM
}
private bool IsRestrictedDestination(string destination)
{
var restrictedDestinations = new[] { "cuba", "north korea", "syria", "iran" };
return restrictedDestinations.Contains(destination.ToLower());
}
private bool IsServiceAvailableToday()
{
var today = DateTime.UtcNow;
return today.DayOfWeek != DayOfWeek.Sunday;
}
}
/// <summary>
/// International shipping strategy
/// </summary>
public class InternationalShippingStrategy : IShippingStrategy
{
public string Name => "International";
public decimal CalculateCost(decimal weight, decimal distance, string destination)
{
var baseCost = (weight * 3.0m + distance * 0.8m) * 1.1m; // 10% international fee
// Customs and handling fees
baseCost += 15m;
// Currency exchange adjustment (simplified)
if (RequiresCurrencyConversion(destination))
{
baseCost *= 1.03m; // 3% exchange fee
}
return Math.Round(baseCost, 2);
}
public TimeSpan EstimateDelivery(decimal distance)
{
var days = (int)Math.Ceiling(distance / 200); // 200 km per day
return TimeSpan.FromDays(Math.Max(days, 7)); // Minimum 7 days for international
}
public bool IsAvailable(string destination)
{
return !IsRestrictedDestination(destination) &&
IsInternationalDestination(destination);
}
private bool RequiresCurrencyConversion(string destination)
{
var nonUsdDestinations = new[] { "europe", "uk", "canada", "australia", "japan" };
return nonUsdDestinations.Any(d => destination.ToLower().Contains(d));
}
private bool IsInternationalDestination(string destination)
{
var usDestinations = new[] { "usa", "united states", "us" };
return !usDestinations.Any(d => destination.ToLower().Contains(d));
}
private bool IsRestrictedDestination(string destination)
{
var restrictedDestinations = new[] { "cuba", "north korea", "syria", "iran", "russia" };
return restrictedDestinations.Any(d => destination.ToLower().Contains(d));
}
}}
Step 3: Strategy Context and Factory

Join the conversation! Your thoughts help the community grow.