Skip to content

SOLID Principles Explained with Real-World Examples

SOLID is a set of five object-oriented design principles that help developers build software that is easier to maintain, extend, test, and refactor. The five principles are: S - Single Responsibility Principle O - Open/C...

Ekanatha Reddy Urivakili27 min1,579 words

SOLID is a set of five object-oriented design principles that help developers build software that is easier to maintain, extend, test, and refactor.

The five principles are:

S - Single Responsibility Principle
O - Open/Closed Principle
L - Liskov Substitution Principle
I - Interface Segregation Principle
D - Dependency Inversion Principle

These principles are especially useful in .NET / C#, Java, TypeScript, and other object-oriented languages.


1. S — Single Responsibility Principle

Meaning

The Single Responsibility Principle says:

A class should have only one reason to change.

In simple words, one class should do one main job.

A class should not be responsible for multiple unrelated things such as authentication, user profile management, sending emails, logging, file handling, and database operations all at once.

Example from the screenshot

The screenshot separates responsibilities into different classes:

UserAuth       -> Login
UserProfile    -> Profile update
EmailService   -> Emails

This is better than having one large UserService class doing everything.


Bad example

public class UserService
{
    public void Login(string username, string password)
    {
        // Validate user credentials
        // Login logic
    }

    public void UpdateProfile(int userId, string name, string email)
    {
        // Update user profile
    }

    public void SendWelcomeEmail(string email)
    {
        // Send welcome email
    }

    public void GenerateUserReport(int userId)
    {
        // Generate report
    }
}

What is wrong here?

UserService has too many responsibilities:

Login
Profile update
Email sending
Report generation

This class can change for many different reasons:

Authentication rule changes
Profile fields change
Email template changes
Report format changes

That violates the Single Responsibility Principle.


Good example

public class UserAuthService
{
    public void Login(string username, string password)
    {
        // Login logic
    }
}

public class UserProfileService
{
    public void UpdateProfile(int userId, string name, string email)
    {
        // Profile update logic
    }
}

public class EmailService
{
    public void SendWelcomeEmail(string email)
    {
        // Email sending logic
    }
}

public class UserReportService
{
    public void GenerateUserReport(int userId)
    {
        // Report generation logic
    }
}

Now each class has one clear responsibility.

Real-world example

Imagine an e-commerce application.

Bad design:

OrderService
 ├── Create order
 ├── Process payment
 ├── Send invoice email
 ├── Update inventory
 └── Generate PDF invoice

Better design:

OrderService        -> Handles order creation
PaymentService      -> Handles payment processing
EmailService        -> Sends emails
InventoryService    -> Updates stock
InvoiceService      -> Generates invoices

Why this matters

Single Responsibility makes your code:

Easier to understand
Easier to test
Easier to debug
Easier to change
Less risky to modify

When a bug appears in email sending, you know it belongs in EmailService, not somewhere inside a huge OrderService.


2. O — Open/Closed Principle

Meaning

The Open/Closed Principle says:

Software entities should be open for extension but closed for modification.

In simple words, you should be able to add new behavior without changing existing working code.

This reduces the risk of breaking existing functionality.


Example from the screenshot

The screenshot shows:

Shape
 ├── Circle
 ├── Rectangle
 └── Triangle

Each shape implements a common Shape interface.

You can add a new shape without changing the existing Shape contract.


Bad example

public class AreaCalculator
{
    public double CalculateArea(object shape)
    {
        if (shape is Circle circle)
        {
            return Math.PI * circle.Radius * circle.Radius;
        }

        if (shape is Rectangle rectangle)
        {
            return rectangle.Width * rectangle.Height;
        }

        if (shape is Triangle triangle)
        {
            return 0.5 * triangle.Base * triangle.Height;
        }

        throw new NotSupportedException("Shape not supported");
    }
}

What is wrong here?

Every time you add a new shape, you must modify AreaCalculator.

For example, if you add:

Square
Pentagon
Ellipse

You need to keep editing the same class.

That violates the Open/Closed Principle.


Good example

public interface IShape
{
    double CalculateArea();
}

public class Circle : IShape
{
    public double Radius { get; set; }

    public double CalculateArea()
    {
        return Math.PI * Radius * Radius;
    }
}

public class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }

    public double CalculateArea()
    {
        return Width * Height;
    }
}

public class Triangle : IShape
{
    public double Base { get; set; }
    public double Height { get; set; }

    public double CalculateArea()
    {
        return 0.5 * Base * Height;
    }
}

Now the calculator can work with any shape:

public class AreaCalculator
{
    public double CalculateArea(IShape shape)
    {
        return shape.CalculateArea();
    }
}

If you want to add a new shape:

public class Square : IShape
{
    public double Side { get; set; }

    public double CalculateArea()
    {
        return Side * Side;
    }
}

You do not need to modify AreaCalculator.

Real-world example

Payment processing is a very common example.

Bad design:

public class PaymentService
{
    public void Pay(string paymentType)
    {
        if (paymentType == "Stripe")
        {
            // Stripe payment logic
        }
        else if (paymentType == "PayPal")
        {
            // PayPal payment logic
        }
        else if (paymentType == "ApplePay")
        {
            // Apple Pay logic
        }
    }
}

Better design:

public interface IPaymentMethod
{
    void Pay(decimal amount);
}

public class StripePayment : IPaymentMethod
{
    public void Pay(decimal amount)
    {
        // Stripe payment logic
    }
}

public class PayPalPayment : IPaymentMethod
{
    public void Pay(decimal amount)
    {
        // PayPal payment logic
    }
}

public class ApplePayPayment : IPaymentMethod
{
    public void Pay(decimal amount)
    {
        // Apple Pay logic
    }
}

Then:

public class PaymentService
{
    public void ProcessPayment(IPaymentMethod paymentMethod, decimal amount)
    {
        paymentMethod.Pay(amount);
    }
}

Why this matters

Open/Closed Principle helps you:

Add new features safely
Avoid modifying tested code
Reduce bugs
Improve maintainability
Support plug-in style design

3. L — Liskov Substitution Principle

Meaning

The Liskov Substitution Principle says:

Objects of a parent type should be replaceable with objects of a child type without breaking the application.

In simple words, a child class should behave correctly when used in place of its parent class.

If a method expects a Bird, then any subclass of Bird should work without unexpected behavior.


Example from the screenshot

The screenshot shows:

Bird
 ├── Eagle
 └── Sparrow

Both Eagle and Sparrow can fly, so this works:

void MakeFly(Bird bird)
{
    bird.Fly();
}

MakeFly(new Eagle());
MakeFly(new Sparrow());

This is valid because both child classes follow the behavior expected from Bird.


Bad example

public class Bird
{
    public virtual void Fly()
    {
        Console.WriteLine("Bird is flying");
    }
}

public class Eagle : Bird
{
    public override void Fly()
    {
        Console.WriteLine("Eagle is flying high");
    }
}

public class Penguin : Bird
{
    public override void Fly()
    {
        throw new NotSupportedException("Penguins cannot fly");
    }
}

Now this method becomes dangerous:

public void MakeBirdFly(Bird bird)
{
    bird.Fly();
}

This works:

MakeBirdFly(new Eagle());

But this fails:

MakeBirdFly(new Penguin());

The problem is that Penguin is a Bird, but it cannot behave like the expected Bird that can fly.

That violates the Liskov Substitution Principle.


Good example

Instead of saying all birds can fly, separate the behavior:

public abstract class Bird
{
    public string Name { get; set; }
}

public interface IFlyingBird
{
    void Fly();
}

public class Eagle : Bird, IFlyingBird
{
    public void Fly()
    {
        Console.WriteLine("Eagle is flying");
    }
}

public class Sparrow : Bird, IFlyingBird
{
    public void Fly()
    {
        Console.WriteLine("Sparrow is flying");
    }
}

public class Penguin : Bird
{
    public void Swim()
    {
        Console.WriteLine("Penguin is swimming");
    }
}

Now the method only accepts birds that can fly:

public void MakeFly(IFlyingBird bird)
{
    bird.Fly();
}

This is correct:

MakeFly(new Eagle());
MakeFly(new Sparrow());

This is not allowed:

MakeFly(new Penguin());

And that is good, because the design prevents incorrect usage.

Real-world example

Consider a banking system.

Bad design:

public class BankAccount
{
    public virtual void Withdraw(decimal amount)
    {
        // Withdraw money
    }
}

public class SavingsAccount : BankAccount
{
    public override void Withdraw(decimal amount)
    {
        // Withdraw money
    }
}

public class FixedDepositAccount : BankAccount
{
    public override void Withdraw(decimal amount)
    {
        throw new NotSupportedException("Cannot withdraw before maturity");
    }
}

This violates Liskov Substitution because FixedDepositAccount cannot be safely used wherever BankAccount is expected.

Better design:

public abstract class BankAccount
{
    public decimal Balance { get; protected set; }
}

public interface IWithdrawable
{
    void Withdraw(decimal amount);
}

public class SavingsAccount : BankAccount, IWithdrawable
{
    public void Withdraw(decimal amount)
    {
        // Withdraw money
    }
}

public class FixedDepositAccount : BankAccount
{
    public DateTime MaturityDate { get; set; }
}

Why this matters

Liskov Substitution helps you:

Avoid unexpected runtime errors
Design correct inheritance hierarchies
Prevent wrong abstractions
Make polymorphism reliable
Improve testability

A good rule is: do not force a child class to support behavior that does not naturally apply to it.


4. I — Interface Segregation Principle

Meaning

The Interface Segregation Principle says:

A class should not be forced to implement methods it does not use.

In simple words, prefer small, focused interfaces instead of large, general-purpose interfaces.


Example from the screenshot

The screenshot separates printer capabilities into multiple interfaces:

Printable
Scannable
Faxable

An all-in-one printer may implement all three.

A simple printer may implement only Printable.


Bad example

public interface IMachine
{
    void Print();
    void Scan();
    void Fax();
}

Now every machine must implement all three methods.

public class AllInOnePrinter : IMachine
{
    public void Print()
    {
        Console.WriteLine("Printing");
    }

    public void Scan()
    {
        Console.WriteLine("Scanning");
    }

    public void Fax()
    {
        Console.WriteLine("Faxing");
    }
}

This works for an all-in-one printer.

But what about a simple printer?

public class SimplePrinter : IMachine
{
    public void Print()
    {
        Console.WriteLine("Printing");
    }

    public void Scan()
    {
        throw new NotSupportedException();
    }

    public void Fax()
    {
        throw new NotSupportedException();
    }
}

This is bad because SimplePrinter is forced to implement Scan and Fax, even though it does not support them.

That violates the Interface Segregation Principle.


Good example

Create smaller interfaces:

public interface IPrintable
{
    void Print();
}

public interface IScannable
{
    void Scan();
}

public interface IFaxable
{
    void Fax();
}

Now each class implements only what it supports.

public class SimplePrinter : IPrintable
{
    public void Print()
    {
        Console.WriteLine("Printing");
    }
}

All-in-one printer:

public class AllInOnePrinter : IPrintable, IScannable, IFaxable
{
    public void Print()
    {
        Console.WriteLine("Printing");
    }

    public void Scan()
    {
        Console.WriteLine("Scanning");
    }

    public void Fax()
    {
        Console.WriteLine("Faxing");
    }
}

Real-world example

Consider a user management system.

Bad interface:

public interface IUserService
{
    void RegisterUser();
    void DeleteUser();
    void SendEmail();
    void GenerateReport();
    void ExportToCsv();
}

This interface is doing too much.

Better design:

public interface IUserRegistrationService
{
    void RegisterUser();
}

public interface IUserDeletionService
{
    void DeleteUser();
}

public interface IUserNotificationService
{
    void SendEmail();
}

public interface IUserReportService
{
    void GenerateReport();
}

public interface IUserExportService
{
    void ExportToCsv();
}

Now classes can implement only the interfaces they need.

Why this matters

Interface Segregation helps you:

Avoid unnecessary methods
Reduce coupling
Improve readability
Make testing easier
Support flexible implementations

A good interface should describe one specific capability.


5. D — Dependency Inversion Principle

Meaning

The Dependency Inversion Principle says:

High-level modules should not depend on low-level modules. Both should depend on abstractions.

It also says:

Abstractions should not depend on details. Details should depend on abstractions.

In simple words, your business logic should depend on interfaces, not concrete classes.


Example from the screenshot

The screenshot shows:

OrderService -> PaymentGateway
PaymentGateway -> Stripe
PaymentGateway -> PayPal

OrderService does not directly depend on Stripe or PayPal.

Instead, it depends on an abstraction:

PaymentGateway

At runtime, you can inject:

Stripe
PayPal

Bad example

public class StripePaymentGateway
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount} using Stripe");
    }
}

public class OrderService
{
    private readonly StripePaymentGateway _stripePaymentGateway;

    public OrderService()
    {
        _stripePaymentGateway = new StripePaymentGateway();
    }

    public void PlaceOrder(decimal amount)
    {
        _stripePaymentGateway.Pay(amount);
    }
}

What is wrong here?

OrderService is tightly coupled to StripePaymentGateway.

If you want to use PayPal, Razorpay, Apple Pay, or another provider, you must modify OrderService.

That violates the Dependency Inversion Principle.


Good example

Create an abstraction:

public interface IPaymentGateway
{
    void Pay(decimal amount);
}

Create implementations:

public class StripePaymentGateway : IPaymentGateway
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount} using Stripe");
    }
}

public class PayPalPaymentGateway : IPaymentGateway
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount} using PayPal");
    }
}

Now OrderService depends on the interface:

public class OrderService
{
    private readonly IPaymentGateway _paymentGateway;

    public OrderService(IPaymentGateway paymentGateway)
    {
        _paymentGateway = paymentGateway;
    }

    public void PlaceOrder(decimal amount)
    {
        _paymentGateway.Pay(amount);
    }
}

Register the dependency in .NET Core:

builder.Services.AddScoped<IPaymentGateway, StripePaymentGateway>();

Later, you can switch to PayPal:

builder.Services.AddScoped<IPaymentGateway, PayPalPaymentGateway>();

No change is needed inside OrderService.

Real-world example

A notification system.

Bad design:

public class NotificationService
{
    private readonly EmailSender _emailSender = new EmailSender();

    public void Notify(string message)
    {
        _emailSender.SendEmail(message);
    }
}

Better design:

public interface INotificationSender
{
    void Send(string message);
}

public class EmailSender : INotificationSender
{
    public void Send(string message)
    {
        Console.WriteLine("Email sent: " + message);
    }
}

public class SmsSender : INotificationSender
{
    public void Send(string message)
    {
        Console.WriteLine("SMS sent: " + message);
    }
}

public class WhatsAppSender : INotificationSender
{
    public void Send(string message)
    {
        Console.WriteLine("WhatsApp sent: " + message);
    }
}

Service:

public class NotificationService
{
    private readonly INotificationSender _sender;

    public NotificationService(INotificationSender sender)
    {
        _sender = sender;
    }

    public void Notify(string message)
    {
        _sender.Send(message);
    }
}

Why this matters

Dependency Inversion helps you:

Reduce tight coupling
Improve unit testing
Support dependency injection
Switch implementations easily
Improve architecture flexibility

This principle is heavily used in ASP.NET Core through built-in dependency injection.


SOLID Principles Summary

PrincipleMeaningMain Benefit
Single ResponsibilityOne class should have one jobEasier maintenance
Open/ClosedAdd new behavior without changing existing codeSafer extension
Liskov SubstitutionChild classes should replace parent classes safelyReliable inheritance
Interface SegregationUse small focused interfacesLess forced implementation
Dependency InversionDepend on abstractions, not concrete classesLoose coupling

Complete Real-World Example: Order Processing System

Let’s apply all SOLID principles to an order processing example.

Requirement

When a customer places an order:

Create order
Take payment
Send confirmation email
Update inventory
Generate invoice

A poor design would put everything into one class:

public class OrderService
{
    public void PlaceOrder()
    {
        // Create order
        // Process payment
        // Send email
        // Update inventory
        // Generate invoice
    }
}

This violates multiple SOLID principles.


Better SOLID-based design

public interface IPaymentGateway
{
    void Pay(decimal amount);
}

public interface IEmailService
{
    void SendEmail(string to, string subject, string body);
}

public interface IInventoryService
{
    void UpdateStock(int productId, int quantity);
}

public interface IInvoiceService
{
    void GenerateInvoice(int orderId);
}

Implementations:

public class StripePaymentGateway : IPaymentGateway
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Payment of {amount} processed by Stripe");
    }
}

public class EmailService : IEmailService
{
    public void SendEmail(string to, string subject, string body)
    {
        Console.WriteLine($"Email sent to {to}");
    }
}

public class InventoryService : IInventoryService
{
    public void UpdateStock(int productId, int quantity)
    {
        Console.WriteLine("Inventory updated");
    }
}

public class InvoiceService : IInvoiceService
{
    public void GenerateInvoice(int orderId)
    {
        Console.WriteLine("Invoice generated");
    }
}

Order service:

public class OrderService
{
    private readonly IPaymentGateway _paymentGateway;
    private readonly IEmailService _emailService;
    private readonly IInventoryService _inventoryService;
    private readonly IInvoiceService _invoiceService;

    public OrderService(
        IPaymentGateway paymentGateway,
        IEmailService emailService,
        IInventoryService inventoryService,
        IInvoiceService invoiceService)
    {
        _paymentGateway = paymentGateway;
        _emailService = emailService;
        _inventoryService = inventoryService;
        _invoiceService = invoiceService;
    }

    public void PlaceOrder(int orderId, int productId, int quantity, decimal amount, string customerEmail)
    {
        _paymentGateway.Pay(amount);
        _inventoryService.UpdateStock(productId, quantity);
        _invoiceService.GenerateInvoice(orderId);
        _emailService.SendEmail(
            customerEmail,
            "Order Confirmation",
            "Your order has been placed successfully.");
    }
}

Dependency injection registration:

builder.Services.AddScoped<IPaymentGateway, StripePaymentGateway>();
builder.Services.AddScoped<IEmailService, EmailService>();
builder.Services.AddScoped<IInventoryService, InventoryService>();
builder.Services.AddScoped<IInvoiceService, InvoiceService>();
builder.Services.AddScoped<OrderService>();

This design is better because:

Payment logic can change without changing OrderService
Email logic is separate
Inventory logic is separate
Invoice logic is separate
Each service can be tested independently
New payment providers can be added easily

How SOLID Helps in .NET Core Projects

SOLID principles are very useful in .NET Core because they work naturally with:

Dependency Injection
Clean Architecture
Vertical Slice Architecture
Domain-Driven Design
Unit Testing
Microservices
CQRS
Event-Driven Architecture

For example:

Controllers depend on services
Services depend on interfaces
Infrastructure implements interfaces
Application layer contains business use cases
Domain layer stays independent

A clean .NET Core project may look like this:

MyApp.Api
 └── Controllers

MyApp.Application
 └── Interfaces
 └── UseCases

MyApp.Domain
 └── Entities
 └── ValueObjects

MyApp.Infrastructure
 └── Repositories
 └── PaymentGateways
 └── EmailServices

Common Mistakes When Applying SOLID

1. Creating too many interfaces

Not every class needs an interface. Use interfaces when you need abstraction, testing flexibility, or multiple implementations.

Bad:

IUser
IUserData
IUserManager
IUserHelper
IUserUtility

Better:

IUserRepository
IEmailService
IPaymentGateway

2. Overengineering simple applications

For a small CRUD app, applying every pattern too heavily can make the code harder to understand.

Start simple, then introduce abstractions when needed.

3. Misusing inheritance

Inheritance should represent a true “is-a” relationship.

Good:

Eagle is a Bird
SavingsAccount is a BankAccount

But behavior must still be valid. A Penguin is a bird, but not a flying bird.

4. Fat interfaces

Avoid interfaces with too many methods.

Bad:

public interface IUserService
{
    void Register();
    void Login();
    void SendEmail();
    void ExportReport();
    void UploadImage();
    void DeleteAccount();
}

Better:

IUserRegistrationService
IAuthenticationService
IEmailService
IReportExportService

5. Depending directly on third-party libraries

Business logic should not directly depend on Stripe, SendGrid, AWS S3, Twilio, or other external services.

Instead, create your own abstraction:

IPaymentGateway
IEmailSender
IFileStorageService
ISmsSender

Final Thoughts

SOLID principles are not strict rules that must be blindly followed everywhere. They are guidelines that help you design better software.

A good developer uses SOLID to reduce complexity, not increase it.

For most .NET Core applications, the goal should be:

Small focused classes
Clear interfaces
Loose coupling
Easy testing
Safe extension
Readable architecture

SOLID is especially powerful when combined with Clean Architecture, Dependency Injection, and Domain-Driven Design.

A simple way to remember SOLID:

S - One class, one responsibility
O - Add new behavior without changing old code
L - Child classes should behave like their parent
I - Small interfaces are better than large interfaces
D - Depend on abstractions, not concrete classes
category: tech-stacks

High-Level Design Diagram of SOLID Principles in an Order Processing System

flowchart TD
    A[OrderService] -->|depends on| B[IPaymentGateway]
    A -->|depends on| C[IEmailService]
    A -->|depends on| D[IInventoryService]
    A -->|depends on| E[IInvoiceService]

    B --> F[StripePaymentGateway]
    B --> G[PayPalPaymentGateway]

    C --> H[EmailService]
    D --> I[InventoryService]
    E --> J[InvoiceService]

High-level dependencies showing how OrderService depends on abstractions, enabling flexible implementations

Sequence Diagram: PlaceOrder Flow Using Dependency Inversion and Single Responsibility

sequenceDiagram
    participant Customer
    participant OrderService
    participant PaymentGateway
    participant InventoryService
    participant InvoiceService
    participant EmailService

    Customer->>OrderService: PlaceOrder(orderId, productId, quantity, amount, customerEmail)
    OrderService->>PaymentGateway: Pay(amount)
    PaymentGateway-->>OrderService: Payment Success
    OrderService->>InventoryService: UpdateStock(productId, quantity)
    InventoryService-->>OrderService: Stock Updated
    OrderService->>InvoiceService: GenerateInvoice(orderId)
    InvoiceService-->>OrderService: Invoice Generated
    OrderService->>EmailService: SendEmail(customerEmail, subject, body)
    EmailService-->>OrderService: Email Sent
    OrderService-->>Customer: Order Placed Successfully

Detailed order placement flow showing interactions between services that each follow single responsibilities and abstract interfaces

Realistic Example 1: Payment Processor Plugin Architecture in .NET Core (Demonstrates O, D, and I principles)

public interface IPaymentProcessor
{
    void ProcessPayment(decimal amount);
}

public class StripeProcessor : IPaymentProcessor
{
    public void ProcessPayment(decimal amount)
    {
        Console.WriteLine($"Stripe processed payment of {amount:C}");
    }
}

public class PayPalProcessor : IPaymentProcessor
{
    public void ProcessPayment(decimal amount)
    {
        Console.WriteLine($"PayPal processed payment of {amount:C}");
    }
}

public class PaymentHandler
{
    private readonly IPaymentProcessor _processor;

    public PaymentHandler(IPaymentProcessor processor)
    {
        _processor = processor;
    }

    public void Handle(decimal amount)
    {
        _processor.ProcessPayment(amount);
    }
}

Notice how adding new payment processors requires no changes to PaymentHandler, fulfilling OCP and DIP by depending on abstractions.

Realistic Example 2: Segregated User Notification Using Interface Segregation Principle with Dependency Injection

public interface IEmailSender
{
    void SendEmail(string to, string subject, string body);
}

public interface ISmsSender
{
    void SendSms(string number, string message);
}

public class EmailSender : IEmailSender
{
    public void SendEmail(string to, string subject, string body)
    {
        Console.WriteLine($"Email sent to {to}: {subject}");
    }
}

public class SmsSender : ISmsSender
{
    public void SendSms(string number, string message)
    {
        Console.WriteLine($"SMS sent to {number}: {message}");
    }
}

public class NotificationService
{
    private readonly IEmailSender _emailSender;
    private readonly ISmsSender _smsSender;

    public NotificationService(IEmailSender emailSender, ISmsSender smsSender)
    {
        _emailSender = emailSender;
        _smsSender = smsSender;
    }

    public void NotifyByEmail(string to, string subject, string body)
    {
        _emailSender.SendEmail(to, subject, body);
    }

    public void NotifyBySms(string number, string message)
    {
        _smsSender.SendSms(number, message);
    }
}

This example respects the Interface Segregation Principle by not forcing implementations to support irrelevant methods.

Observability for SOLID-Based Architectures

What to Log

  • Service entry/exit: Log method invocations with correlation IDs.
  • Dependency calls: Log calls to injected services with parameters (avoid sensitive data).
  • Errors and exceptions: Structured errors with stack traces.
  • Configuration loaded: Log which implementations are injected at startup.
  • Performance metrics: Duration of each service method call.

Structured Log Example

{
  "timestamp": "2024-06-01T12:34:56Z",
  "level": "Information",
  "service": "OrderService",
  "method": "PlaceOrder",
  "orderId": 12345,
  "message": "Order placed successfully",
  "durationMs": 215,
  "correlationId": "abc-xyz-123",
  "dependencies": {
    "PaymentGateway": "StripePaymentGateway",
    "EmailService": "EmailService"
  }
}

Key Metrics to Collect (using RED and USE principles)

MetricPurposeCollect From
Request RateNumber of incoming requests per serviceOrderService, PaymentGateway etc.
Error RateNumber of failed requests or exceptionsAll services
DurationLatency per request (avg, p95, max)Service methods
Resource UtilizationCPU, Memory, Threads, GC pause timesHosting environment
Dependency LatencyTime spent in dependent service callsOrderService calls to interfaces

Distributed Tracing with OpenTelemetry (.NET Example)

using OpenTelemetry.Trace;
using OpenTelemetry.Resources;

var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("OrderProcessingService"))
    .AddAspNetCoreInstrumentation()
    .AddHttpClientInstrumentation()
    .AddConsoleExporter()
    .Build();

Use spans to trace calls through services:

public class OrderService
{
    private readonly Tracer _tracer;

    public OrderService(Tracer tracer, IPaymentGateway paymentGateway, ...)
    {
        _tracer = tracer;
        ...
    }

    public void PlaceOrder(...)
    {
        using var span = _tracer.StartActiveSpan("PlaceOrder");
        ...
        _paymentGateway.Pay(amount);
        ...
    }
}

Suggested SLI and SLO Table

SLISLO TargetNotes
Successful order placements99.9% over 30 daysIncludes payment, email sent
Average order process latency< 500 msMeasured end-to-end
Payment gateway error rate< 0.1%Important for customer trust
Dependency call latency< 100 ms per serviceTo prevent cascading delays

Alerts Worth Paging

  • Payment gateway failures exceed threshold (>0.5% errors in 5m windows)
  • Order placement latency exceeds 1 second
  • EmailService failing to send emails consistently
  • High CPU or memory resource usage in critical services
  • Errors in distributed tracing indicating failures or exceptions

These diagrams, realistic code examples, and observability guidance complete the original article by illustrating how SOLID principles concretely translate into clean, testable, and maintainable software architecture in modern .NET Core projects.