
Solid Principles
- 7 installs
- 4 repo stars
- Updated June 18, 2026
- doubleslashse/claude-marketplace
Apply the five SOLID design principles when designing .NET classes, interfaces, and object relationships.
About
Explains the five SOLID principles for maintainable, testable, extensible .NET code. A developer uses it when designing classes and interfaces or reviewing object-oriented design.
- Covers all five SOLID principles
- Targets maintainable, testable .NET design
Solid Principles by the numbers
- 7 all-time installs (skills.sh)
- Ranked #852 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Data as of Jul 29, 2026 (Skillselion catalog sync)
npx skills add https://github.com/doubleslashse/claude-marketplace --skill solid-principlesAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 7 |
|---|---|
| repo stars | ★ 4 |
| Last updated | June 18, 2026 |
| Repository | doubleslashse/claude-marketplace ↗ |
What it does
Apply the five SOLID design principles when designing .NET classes, interfaces, and object relationships.
Files
SOLID Principles for .NET
Overview
SOLID is an acronym for five principles that lead to maintainable, testable, and extensible object-oriented code.
| Principle | Summary |
|---|---|
| S - Single Responsibility | One class, one reason to change |
| O - Open/Closed | Open for extension, closed for modification |
| L - Liskov Substitution | Subtypes must be substitutable for base types |
| I - Interface Segregation | Many specific interfaces > one general interface |
| D - Dependency Inversion | Depend on abstractions, not concretions |
---
S - Single Responsibility Principle (SRP)
A class should have only one reason to change.
Violation Example
// BAD: Multiple responsibilities
public class OrderService
{
public Order CreateOrder(OrderRequest request)
{
// Validation logic
if (string.IsNullOrEmpty(request.CustomerEmail))
throw new ValidationException("Email required");
// Business logic
var order = new Order
{
Id = Guid.NewGuid(),
Items = request.Items,
Total = CalculateTotal(request.Items)
};
// Persistence logic
using var connection = new SqlConnection(_connectionString);
connection.Execute("INSERT INTO Orders...", order);
// Notification logic
var emailBody = $"Order {order.Id} confirmed!";
_smtpClient.Send(request.CustomerEmail, "Order Confirmed", emailBody);
// Logging logic
File.AppendAllText("orders.log", $"{DateTime.Now}: Order {order.Id} created");
return order;
}
}Correct Implementation
// GOOD: Single responsibility per class
public class OrderService
{
private readonly IOrderValidator _validator;
private readonly IOrderRepository _repository;
private readonly IOrderNotifier _notifier;
private readonly ILogger<OrderService> _logger;
public OrderService(
IOrderValidator validator,
IOrderRepository repository,
IOrderNotifier notifier,
ILogger<OrderService> logger)
{
_validator = validator;
_repository = repository;
_notifier = notifier;
_logger = logger;
}
public async Task<Order> CreateOrderAsync(OrderRequest request)
{
_validator.Validate(request);
var order = Order.Create(request.Items);
await _repository.AddAsync(order);
await _notifier.NotifyOrderCreatedAsync(order, request.CustomerEmail);
_logger.LogInformation("Order {OrderId} created", order.Id);
return order;
}
}
// Each concern in its own class
public class OrderValidator : IOrderValidator
{
public void Validate(OrderRequest request)
{
if (string.IsNullOrEmpty(request.CustomerEmail))
throw new ValidationException("Email required");
}
}
public class OrderRepository : IOrderRepository
{
private readonly DbContext _context;
public async Task AddAsync(Order order)
{
_context.Orders.Add(order);
await _context.SaveChangesAsync();
}
}
public class EmailOrderNotifier : IOrderNotifier
{
private readonly IEmailService _emailService;
public async Task NotifyOrderCreatedAsync(Order order, string email)
{
await _emailService.SendAsync(email, "Order Confirmed", $"Order {order.Id} confirmed!");
}
}SRP Test: Ask These Questions
1. Can I describe what the class does without using "and"? 2. Would different stakeholders want changes to this class? 3. Does the class have more than 200-300 lines?
---
O - Open/Closed Principle (OCP)
Software entities should be open for extension but closed for modification.
Violation Example
// BAD: Must modify class to add new discount types
public class DiscountCalculator
{
public decimal Calculate(Order order, string discountType)
{
switch (discountType)
{
case "percentage":
return order.Total * 0.1m;
case "fixed":
return 10m;
case "loyalty":
return order.Total * 0.15m;
// Every new discount requires modifying this class
default:
return 0m;
}
}
}Correct Implementation
// GOOD: Extensible without modification
public interface IDiscountStrategy
{
decimal Calculate(Order order);
}
public class PercentageDiscount : IDiscountStrategy
{
private readonly decimal _percentage;
public PercentageDiscount(decimal percentage) => _percentage = percentage;
public decimal Calculate(Order order) => order.Total * _percentage;
}
public class FixedDiscount : IDiscountStrategy
{
private readonly decimal _amount;
public FixedDiscount(decimal amount) => _amount = amount;
public decimal Calculate(Order order) => Math.Min(_amount, order.Total);
}
public class LoyaltyDiscount : IDiscountStrategy
{
private readonly ILoyaltyService _loyaltyService;
public LoyaltyDiscount(ILoyaltyService loyaltyService) => _loyaltyService = loyaltyService;
public decimal Calculate(Order order)
{
var tier = _loyaltyService.GetCustomerTier(order.CustomerId);
return tier switch
{
LoyaltyTier.Gold => order.Total * 0.15m,
LoyaltyTier.Silver => order.Total * 0.10m,
_ => 0m
};
}
}
// New discounts added without touching existing code
public class BulkDiscount : IDiscountStrategy
{
public decimal Calculate(Order order)
{
if (order.Items.Count >= 10)
return order.Total * 0.20m;
return 0m;
}
}
// Calculator is closed for modification
public class DiscountCalculator
{
public decimal Calculate(Order order, IDiscountStrategy strategy)
{
return strategy.Calculate(order);
}
}OCP Patterns
- Strategy Pattern (as shown above)
- Template Method Pattern
- Decorator Pattern
- Plugin Architecture
---
L - Liskov Substitution Principle (LSP)
Objects of a superclass should be replaceable with objects of its subclasses without breaking the application.
Violation Example
// BAD: Square violates Rectangle's contract
public class Rectangle
{
public virtual int Width { get; set; }
public virtual int Height { get; set; }
public int CalculateArea() => Width * Height;
}
public class Square : Rectangle
{
public override int Width
{
get => base.Width;
set
{
base.Width = value;
base.Height = value; // Unexpected side effect!
}
}
public override int Height
{
get => base.Height;
set
{
base.Height = value;
base.Width = value; // Unexpected side effect!
}
}
}
// This test fails for Square!
[Fact]
public void Rectangle_SetDimensions_CalculatesCorrectArea()
{
Rectangle rect = new Square(); // Substitution
rect.Width = 5;
rect.Height = 4;
Assert.Equal(20, rect.CalculateArea()); // Fails! Returns 16
}Correct Implementation
// GOOD: Separate abstractions
public interface IShape
{
int CalculateArea();
}
public class Rectangle : IShape
{
public int Width { get; }
public int Height { get; }
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
public int CalculateArea() => Width * Height;
}
public class Square : IShape
{
public int Side { get; }
public Square(int side) => Side = side;
public int CalculateArea() => Side * Side;
}
// Both work correctly with the abstraction
public class AreaCalculator
{
public int TotalArea(IEnumerable<IShape> shapes)
{
return shapes.Sum(s => s.CalculateArea());
}
}LSP Rules
1. Preconditions cannot be strengthened in subtype 2. Postconditions cannot be weakened in subtype 3. Invariants must be preserved in subtype 4. History constraint (no unexpected state changes)
Common LSP Violations
// BAD: Throwing NotSupportedException
public class ReadOnlyCollection<T> : ICollection<T>
{
public void Add(T item) => throw new NotSupportedException();
}
// BAD: Ignoring base class behavior
public class CachedRepository : Repository
{
public override void Save(Entity entity)
{
// Doesn't call base.Save() - breaks persistence!
_cache.Add(entity);
}
}---
I - Interface Segregation Principle (ISP)
Clients should not be forced to depend on interfaces they do not use.
Violation Example
// BAD: Fat interface
public interface IWorker
{
void Work();
void Eat();
void Sleep();
void AttendMeeting();
void WriteCode();
void ManageTeam();
}
// Robot can't eat or sleep!
public class Robot : IWorker
{
public void Work() { /* OK */ }
public void Eat() => throw new NotSupportedException();
public void Sleep() => throw new NotSupportedException();
public void AttendMeeting() => throw new NotSupportedException();
public void WriteCode() { /* OK */ }
public void ManageTeam() => throw new NotSupportedException();
}Correct Implementation
// GOOD: Segregated interfaces
public interface IWorkable
{
void Work();
}
public interface IFeedable
{
void Eat();
}
public interface ISleepable
{
void Sleep();
}
public interface IMeetingAttendee
{
void AttendMeeting();
}
public interface IDeveloper : IWorkable
{
void WriteCode();
}
public interface IManager : IWorkable, IMeetingAttendee
{
void ManageTeam();
}
// Clean implementations
public class HumanDeveloper : IDeveloper, IFeedable, ISleepable
{
public void Work() { }
public void WriteCode() { }
public void Eat() { }
public void Sleep() { }
}
public class Robot : IDeveloper
{
public void Work() { }
public void WriteCode() { }
// No forced empty implementations!
}Repository ISP Example
// BAD: Monolithic repository
public interface IRepository<T>
{
T GetById(int id);
IEnumerable<T> GetAll();
void Add(T entity);
void Update(T entity);
void Delete(T entity);
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
void BulkInsert(IEnumerable<T> entities);
void ExecuteRawSql(string sql);
}
// GOOD: Segregated repositories
public interface IReadRepository<T>
{
T? GetById(int id);
IEnumerable<T> GetAll();
}
public interface IWriteRepository<T>
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
}
public interface IQueryRepository<T>
{
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
}
// Compose as needed
public interface IOrderRepository : IReadRepository<Order>, IWriteRepository<Order> { }
public interface IReportRepository : IReadRepository<Report>, IQueryRepository<Report> { }---
D - Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Violation Example
// BAD: High-level depends on low-level
public class OrderService
{
private readonly SqlOrderRepository _repository; // Concrete!
private readonly SmtpEmailSender _emailSender; // Concrete!
public OrderService()
{
_repository = new SqlOrderRepository("connection-string");
_emailSender = new SmtpEmailSender("smtp.server.com");
}
public void CreateOrder(Order order)
{
_repository.Save(order);
_emailSender.Send(order.CustomerEmail, "Order Created");
}
}Correct Implementation
// GOOD: Depend on abstractions
public interface IOrderRepository
{
Task SaveAsync(Order order);
Task<Order?> GetByIdAsync(Guid id);
}
public interface INotificationService
{
Task SendAsync(string recipient, string subject, string message);
}
public class OrderService
{
private readonly IOrderRepository _repository;
private readonly INotificationService _notificationService;
// Dependencies injected via constructor
public OrderService(
IOrderRepository repository,
INotificationService notificationService)
{
_repository = repository;
_notificationService = notificationService;
}
public async Task CreateOrderAsync(Order order)
{
await _repository.SaveAsync(order);
await _notificationService.SendAsync(
order.CustomerEmail,
"Order Created",
$"Your order {order.Id} has been created.");
}
}
// Low-level modules implement abstractions
public class SqlOrderRepository : IOrderRepository
{
private readonly DbContext _context;
public SqlOrderRepository(DbContext context) => _context = context;
public async Task SaveAsync(Order order)
{
_context.Orders.Add(order);
await _context.SaveChangesAsync();
}
public async Task<Order?> GetByIdAsync(Guid id)
{
return await _context.Orders.FindAsync(id);
}
}
public class EmailNotificationService : INotificationService
{
private readonly IEmailClient _emailClient;
public EmailNotificationService(IEmailClient emailClient) => _emailClient = emailClient;
public async Task SendAsync(string recipient, string subject, string message)
{
await _emailClient.SendEmailAsync(recipient, subject, message);
}
}
// Registration in DI container
services.AddScoped<IOrderRepository, SqlOrderRepository>();
services.AddScoped<INotificationService, EmailNotificationService>();
services.AddScoped<OrderService>();DIP Benefits
1. Testability: Mock dependencies easily 2. Flexibility: Swap implementations without changing consumers 3. Maintainability: Changes isolated to implementations 4. Parallel development: Teams work on interfaces
---
Quick Reference
| Principle | Violation Sign | Fix |
|---|---|---|
| SRP | Class has multiple reasons to change | Extract classes by responsibility |
| OCP | Adding features requires modifying existing code | Use abstractions and composition |
| LSP | Subclass can't substitute base class | Fix inheritance or use composition |
| ISP | Implementations throw NotSupported | Split large interfaces |
| DIP | High-level creates low-level instances | Inject dependencies via interfaces |
See examples.md for more comprehensive examples.
SOLID Principles - Comprehensive Examples
Real-World Refactoring: E-Commerce Order System
Before: SOLID Violations
// This class violates ALL SOLID principles
public class OrderProcessor
{
private readonly string _connectionString;
private readonly string _smtpServer;
public OrderProcessor()
{
_connectionString = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
_smtpServer = ConfigurationManager.AppSettings["SmtpServer"];
}
public string ProcessOrder(
int customerId,
List<(int productId, int quantity)> items,
string paymentType)
{
// Validation (SRP violation - validation logic)
if (items == null || items.Count == 0)
return "Error: No items";
using var connection = new SqlConnection(_connectionString);
connection.Open();
// Get customer (DIP violation - direct SQL dependency)
var customer = connection.QuerySingle<Customer>(
"SELECT * FROM Customers WHERE Id = @Id", new { Id = customerId });
if (customer == null)
return "Error: Customer not found";
// Calculate totals (SRP violation - business logic)
decimal total = 0;
foreach (var (productId, quantity) in items)
{
var product = connection.QuerySingle<Product>(
"SELECT * FROM Products WHERE Id = @Id", new { Id = productId });
total += product.Price * quantity;
}
// Apply discount (OCP violation - hardcoded discount types)
decimal discount = 0;
if (customer.Type == "Gold")
discount = total * 0.15m;
else if (customer.Type == "Silver")
discount = total * 0.10m;
else if (customer.Type == "Bronze")
discount = total * 0.05m;
// Adding new customer types requires modifying this method
// Process payment (OCP violation - hardcoded payment types)
bool paymentSuccess;
if (paymentType == "CreditCard")
{
paymentSuccess = ProcessCreditCard(total - discount);
}
else if (paymentType == "PayPal")
{
paymentSuccess = ProcessPayPal(total - discount);
}
else
{
return "Error: Unknown payment type";
}
if (!paymentSuccess)
return "Error: Payment failed";
// Save order (SRP violation - persistence logic)
var orderId = Guid.NewGuid().ToString();
connection.Execute(
"INSERT INTO Orders (Id, CustomerId, Total) VALUES (@Id, @CustomerId, @Total)",
new { Id = orderId, CustomerId = customerId, Total = total - discount });
// Send email (SRP violation - notification logic)
using var smtp = new SmtpClient(_smtpServer);
smtp.Send("orders@store.com", customer.Email, "Order Confirmed", $"Order {orderId}");
// Log (SRP violation - logging logic)
File.AppendAllText("orders.log", $"{DateTime.Now}: Order {orderId} processed\n");
return orderId;
}
private bool ProcessCreditCard(decimal amount) { /* ... */ return true; }
private bool ProcessPayPal(decimal amount) { /* ... */ return true; }
}After: SOLID-Compliant Design
// === ABSTRACTIONS (DIP) ===
public interface IOrderRepository
{
Task<Order> CreateAsync(Order order);
}
public interface ICustomerRepository
{
Task<Customer?> GetByIdAsync(int id);
}
public interface IProductRepository
{
Task<Product?> GetByIdAsync(int id);
}
public interface IDiscountStrategy
{
decimal Calculate(Customer customer, decimal orderTotal);
}
public interface IPaymentProcessor
{
string PaymentType { get; }
Task<PaymentResult> ProcessAsync(decimal amount);
}
public interface INotificationService
{
Task NotifyOrderCreatedAsync(Order order, Customer customer);
}
// === VALUE OBJECTS ===
public record OrderItem(int ProductId, string ProductName, int Quantity, decimal UnitPrice)
{
public decimal Total => Quantity * UnitPrice;
}
public record PaymentResult(bool Success, string? TransactionId, string? ErrorMessage);
// === ENTITIES ===
public class Order
{
public Guid Id { get; private set; }
public int CustomerId { get; private set; }
public IReadOnlyList<OrderItem> Items => _items.AsReadOnly();
public decimal Subtotal => _items.Sum(i => i.Total);
public decimal Discount { get; private set; }
public decimal Total => Subtotal - Discount;
public OrderStatus Status { get; private set; }
private readonly List<OrderItem> _items = new();
private Order() { } // For EF
public static Order Create(int customerId) => new()
{
Id = Guid.NewGuid(),
CustomerId = customerId,
Status = OrderStatus.Pending
};
public void AddItem(Product product, int quantity)
{
_items.Add(new OrderItem(product.Id, product.Name, quantity, product.Price));
}
public void ApplyDiscount(decimal discount)
{
Discount = Math.Min(discount, Subtotal);
}
public void MarkAsPaid(string transactionId)
{
Status = OrderStatus.Paid;
}
}
// === DISCOUNT STRATEGIES (OCP) ===
public class CustomerTierDiscountStrategy : IDiscountStrategy
{
public decimal Calculate(Customer customer, decimal orderTotal)
{
return customer.Tier switch
{
CustomerTier.Gold => orderTotal * 0.15m,
CustomerTier.Silver => orderTotal * 0.10m,
CustomerTier.Bronze => orderTotal * 0.05m,
_ => 0m
};
}
}
public class FirstOrderDiscountStrategy : IDiscountStrategy
{
public decimal Calculate(Customer customer, decimal orderTotal)
{
return customer.OrderCount == 0 ? orderTotal * 0.20m : 0m;
}
}
public class CompositeDiscountStrategy : IDiscountStrategy
{
private readonly IEnumerable<IDiscountStrategy> _strategies;
private readonly DiscountCombination _combination;
public CompositeDiscountStrategy(
IEnumerable<IDiscountStrategy> strategies,
DiscountCombination combination = DiscountCombination.Max)
{
_strategies = strategies;
_combination = combination;
}
public decimal Calculate(Customer customer, decimal orderTotal)
{
var discounts = _strategies.Select(s => s.Calculate(customer, orderTotal));
return _combination switch
{
DiscountCombination.Max => discounts.Max(),
DiscountCombination.Sum => discounts.Sum(),
_ => discounts.Max()
};
}
}
// === PAYMENT PROCESSORS (OCP) ===
public class CreditCardPaymentProcessor : IPaymentProcessor
{
private readonly ICreditCardGateway _gateway;
public string PaymentType => "CreditCard";
public CreditCardPaymentProcessor(ICreditCardGateway gateway) => _gateway = gateway;
public async Task<PaymentResult> ProcessAsync(decimal amount)
{
var result = await _gateway.ChargeAsync(amount);
return new PaymentResult(result.Success, result.TransactionId, result.Error);
}
}
public class PayPalPaymentProcessor : IPaymentProcessor
{
private readonly IPayPalClient _client;
public string PaymentType => "PayPal";
public PayPalPaymentProcessor(IPayPalClient client) => _client = client;
public async Task<PaymentResult> ProcessAsync(decimal amount)
{
var result = await _client.CreatePaymentAsync(amount);
return new PaymentResult(result.Approved, result.PaymentId, result.Message);
}
}
// Adding new payment types is easy!
public class CryptoPaymentProcessor : IPaymentProcessor
{
public string PaymentType => "Crypto";
public async Task<PaymentResult> ProcessAsync(decimal amount) { /* ... */ }
}
// === PAYMENT PROCESSOR FACTORY ===
public interface IPaymentProcessorFactory
{
IPaymentProcessor Create(string paymentType);
}
public class PaymentProcessorFactory : IPaymentProcessorFactory
{
private readonly IEnumerable<IPaymentProcessor> _processors;
public PaymentProcessorFactory(IEnumerable<IPaymentProcessor> processors)
{
_processors = processors;
}
public IPaymentProcessor Create(string paymentType)
{
var processor = _processors.FirstOrDefault(p => p.PaymentType == paymentType);
if (processor == null)
throw new NotSupportedException($"Payment type '{paymentType}' is not supported.");
return processor;
}
}
// === VALIDATORS (SRP) ===
public interface IOrderValidator
{
Task<ValidationResult> ValidateAsync(CreateOrderRequest request);
}
public class OrderValidator : IOrderValidator
{
private readonly ICustomerRepository _customerRepository;
private readonly IProductRepository _productRepository;
public OrderValidator(
ICustomerRepository customerRepository,
IProductRepository productRepository)
{
_customerRepository = customerRepository;
_productRepository = productRepository;
}
public async Task<ValidationResult> ValidateAsync(CreateOrderRequest request)
{
var errors = new List<string>();
if (request.Items == null || request.Items.Count == 0)
errors.Add("Order must contain at least one item.");
var customer = await _customerRepository.GetByIdAsync(request.CustomerId);
if (customer == null)
errors.Add($"Customer {request.CustomerId} not found.");
foreach (var item in request.Items ?? Enumerable.Empty<OrderItemRequest>())
{
var product = await _productRepository.GetByIdAsync(item.ProductId);
if (product == null)
errors.Add($"Product {item.ProductId} not found.");
}
return new ValidationResult(errors.Count == 0, errors);
}
}
// === ORDER SERVICE (SRP - Orchestration Only) ===
public class OrderService
{
private readonly IOrderValidator _validator;
private readonly ICustomerRepository _customerRepository;
private readonly IProductRepository _productRepository;
private readonly IOrderRepository _orderRepository;
private readonly IDiscountStrategy _discountStrategy;
private readonly IPaymentProcessorFactory _paymentFactory;
private readonly INotificationService _notificationService;
private readonly ILogger<OrderService> _logger;
public OrderService(
IOrderValidator validator,
ICustomerRepository customerRepository,
IProductRepository productRepository,
IOrderRepository orderRepository,
IDiscountStrategy discountStrategy,
IPaymentProcessorFactory paymentFactory,
INotificationService notificationService,
ILogger<OrderService> logger)
{
_validator = validator;
_customerRepository = customerRepository;
_productRepository = productRepository;
_orderRepository = orderRepository;
_discountStrategy = discountStrategy;
_paymentFactory = paymentFactory;
_notificationService = notificationService;
_logger = logger;
}
public async Task<Result<Order>> CreateOrderAsync(CreateOrderRequest request)
{
// Validate
var validation = await _validator.ValidateAsync(request);
if (!validation.IsValid)
return Result<Order>.Failure(validation.Errors);
// Get customer
var customer = await _customerRepository.GetByIdAsync(request.CustomerId);
// Build order
var order = Order.Create(request.CustomerId);
foreach (var item in request.Items)
{
var product = await _productRepository.GetByIdAsync(item.ProductId);
order.AddItem(product!, item.Quantity);
}
// Apply discount
var discount = _discountStrategy.Calculate(customer!, order.Subtotal);
order.ApplyDiscount(discount);
// Process payment
var paymentProcessor = _paymentFactory.Create(request.PaymentType);
var paymentResult = await paymentProcessor.ProcessAsync(order.Total);
if (!paymentResult.Success)
return Result<Order>.Failure($"Payment failed: {paymentResult.ErrorMessage}");
order.MarkAsPaid(paymentResult.TransactionId!);
// Persist
await _orderRepository.CreateAsync(order);
// Notify
await _notificationService.NotifyOrderCreatedAsync(order, customer!);
_logger.LogInformation("Order {OrderId} created for customer {CustomerId}", order.Id, customer!.Id);
return Result<Order>.Success(order);
}
}
// === DI REGISTRATION ===
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddOrderServices(this IServiceCollection services)
{
// Repositories
services.AddScoped<ICustomerRepository, SqlCustomerRepository>();
services.AddScoped<IProductRepository, SqlProductRepository>();
services.AddScoped<IOrderRepository, SqlOrderRepository>();
// Validators
services.AddScoped<IOrderValidator, OrderValidator>();
// Discount strategies
services.AddScoped<IDiscountStrategy>(sp =>
new CompositeDiscountStrategy(new IDiscountStrategy[]
{
new CustomerTierDiscountStrategy(),
new FirstOrderDiscountStrategy()
}));
// Payment processors
services.AddScoped<IPaymentProcessor, CreditCardPaymentProcessor>();
services.AddScoped<IPaymentProcessor, PayPalPaymentProcessor>();
services.AddScoped<IPaymentProcessorFactory, PaymentProcessorFactory>();
// Notifications
services.AddScoped<INotificationService, EmailNotificationService>();
// Main service
services.AddScoped<OrderService>();
return services;
}
}Testing the SOLID Design
public class OrderServiceTests
{
private readonly Mock<IOrderValidator> _mockValidator;
private readonly Mock<ICustomerRepository> _mockCustomerRepo;
private readonly Mock<IProductRepository> _mockProductRepo;
private readonly Mock<IOrderRepository> _mockOrderRepo;
private readonly Mock<IDiscountStrategy> _mockDiscount;
private readonly Mock<IPaymentProcessorFactory> _mockPaymentFactory;
private readonly Mock<INotificationService> _mockNotifier;
private readonly OrderService _sut;
public OrderServiceTests()
{
_mockValidator = new Mock<IOrderValidator>();
_mockCustomerRepo = new Mock<ICustomerRepository>();
_mockProductRepo = new Mock<IProductRepository>();
_mockOrderRepo = new Mock<IOrderRepository>();
_mockDiscount = new Mock<IDiscountStrategy>();
_mockPaymentFactory = new Mock<IPaymentProcessorFactory>();
_mockNotifier = new Mock<INotificationService>();
_sut = new OrderService(
_mockValidator.Object,
_mockCustomerRepo.Object,
_mockProductRepo.Object,
_mockOrderRepo.Object,
_mockDiscount.Object,
_mockPaymentFactory.Object,
_mockNotifier.Object,
Mock.Of<ILogger<OrderService>>());
}
[Fact]
public async Task CreateOrder_WithValidRequest_ReturnsSuccessfulOrder()
{
// Arrange
var request = CreateValidRequest();
SetupValidScenario();
// Act
var result = await _sut.CreateOrderAsync(request);
// Assert
Assert.True(result.IsSuccess);
Assert.NotNull(result.Value);
}
[Fact]
public async Task CreateOrder_WithInvalidRequest_ReturnsFailure()
{
// Arrange
var request = CreateValidRequest();
_mockValidator
.Setup(v => v.ValidateAsync(request))
.ReturnsAsync(ValidationResult.Failure("Invalid"));
// Act
var result = await _sut.CreateOrderAsync(request);
// Assert
Assert.False(result.IsSuccess);
}
[Fact]
public async Task CreateOrder_WhenPaymentFails_ReturnsFailure()
{
// Arrange
var request = CreateValidRequest();
SetupValidScenario();
SetupPaymentFailure();
// Act
var result = await _sut.CreateOrderAsync(request);
// Assert
Assert.False(result.IsSuccess);
Assert.Contains("Payment failed", result.Error);
}
private void SetupValidScenario()
{
_mockValidator
.Setup(v => v.ValidateAsync(It.IsAny<CreateOrderRequest>()))
.ReturnsAsync(ValidationResult.Success);
_mockCustomerRepo
.Setup(r => r.GetByIdAsync(It.IsAny<int>()))
.ReturnsAsync(new Customer { Id = 1, Email = "test@test.com" });
_mockProductRepo
.Setup(r => r.GetByIdAsync(It.IsAny<int>()))
.ReturnsAsync(new Product { Id = 1, Name = "Test", Price = 10.00m });
var mockProcessor = new Mock<IPaymentProcessor>();
mockProcessor
.Setup(p => p.ProcessAsync(It.IsAny<decimal>()))
.ReturnsAsync(new PaymentResult(true, "txn123", null));
_mockPaymentFactory
.Setup(f => f.Create(It.IsAny<string>()))
.Returns(mockProcessor.Object);
}
private void SetupPaymentFailure()
{
var mockProcessor = new Mock<IPaymentProcessor>();
mockProcessor
.Setup(p => p.ProcessAsync(It.IsAny<decimal>()))
.ReturnsAsync(new PaymentResult(false, null, "Insufficient funds"));
_mockPaymentFactory
.Setup(f => f.Create(It.IsAny<string>()))
.Returns(mockProcessor.Object);
}
private CreateOrderRequest CreateValidRequest() => new()
{
CustomerId = 1,
Items = new[] { new OrderItemRequest { ProductId = 1, Quantity = 2 } },
PaymentType = "CreditCard"
};
}