Design Patterns and How to Use Them in .NET 9 Applications

Design patterns are proven solutions to common software design problems. They help you write:

  • Clean code
  • Maintainable systems
  • Scalable applications

In modern development with .NET 9, design patterns are widely used in:

  • ASP.NET Core APIs
  • Microservices
  • Blazor applications
  • Enterprise systems

What Are Design Patterns?

Design patterns are templates or best practices, not ready-made code.

They solve problems like:

  • Object creation
  • Code structure
  • Communication between components

Types of Design Patterns

1. Creational Patterns

Handle object creation

  • Singleton
  • Factory
  • Builder

2. Structural Patterns

Organize classes and objects

  • Adapter
  • Decorator
  • Facade

3. Behavioral Patterns

Manage communication

  • Observer
  • Strategy
  • Mediator

Most Useful Patterns in .NET 9 (with Examples)

1. Singleton Pattern

Use Case

  • Logging service
  • Configuration manager

Example

public class Logger
{
    private static Logger _instance;

    private Logger() { }

    public static Logger Instance
    {
        get
        {
            if (_instance == null)
                _instance = new Logger();

            return _instance;
        }
    }

    public void Log(string message)
    {
        Console.WriteLine(message);
    }
}

.NET 9 Best Practice

Use Dependency Injection instead:

builder.Services.AddSingleton<Logger>();

2. Factory Pattern

Use Case

  • Creating objects based on conditions

Example

public interface INotification
{
    void Send();
}

public class EmailNotification : INotification
{
    public void Send() => Console.WriteLine("Email Sent");
}

public class SmsNotification : INotification
{
    public void Send() => Console.WriteLine("SMS Sent");
}

public class NotificationFactory
{
    public static INotification Create(string type)
    {
        return type switch
        {
            "email" => new EmailNotification(),
            "sms" => new SmsNotification(),
            _ => throw new Exception("Invalid type")
        };
    }
}

3. Repository Pattern

Use Case

  • Data access abstraction

Example

public interface IProductRepository
{
    Task<Product> GetById(int id);
}

public class ProductRepository : IProductRepository
{
    public async Task<Product> GetById(int id)
    {
        // DB logic here
        return new Product();
    }
}

Register in .NET 9:

builder.Services.AddScoped<IProductRepository, ProductRepository>();

4. Dependency Injection (DI)

Built-in in .NET 9

Core of modern .NET apps

public class OrderService
{
    private readonly IProductRepository _repo;

    public OrderService(IProductRepository repo)
    {
        _repo = repo;
    }
}

Benefit

  • Loose coupling
  • Easy testing
  • Clean architecture

5. Strategy Pattern

Use Case

  • Multiple algorithms (runtime selection)

Example

public interface IPaymentStrategy
{
    void Pay();
}

public class CreditCardPayment : IPaymentStrategy
{
    public void Pay() => Console.WriteLine("Paid via Credit Card");
}

public class UpiPayment : IPaymentStrategy
{
    public void Pay() => Console.WriteLine("Paid via UPI");
}

Usage:

public class PaymentContext
{
    private readonly IPaymentStrategy _strategy;

    public PaymentContext(IPaymentStrategy strategy)
    {
        _strategy = strategy;
    }

    public void Execute() => _strategy.Pay();
}

6. Observer Pattern

Use Case

  • Event-driven systems
  • Notifications

Example (using events)

public class Publisher
{
    public event Action OnChange;

    public void Notify()
    {
        OnChange?.Invoke();
    }
}

7. Mediator Pattern (Used in CQRS)

Common with libraries like MediatR

Use Case

  • Decoupling components
public class CreateOrderCommand
{
    public int Id { get; set; }
}

Real-World Architecture in .NET 9

Typical clean architecture uses:

  • Controller → Service → Repository
  • DI + Factory + Strategy combined

Common Mistakes

  • Overusing patterns (over-engineering)
  • Using Singleton incorrectly (thread issues)
  • Ignoring built-in DI
  • Mixing business logic with data access

When to Use Patterns?

Problem Pattern
Object creation logic Factory
Shared instance Singleton
Multiple behaviors Strategy
Loose coupling DI
Data abstraction Repository

Interview Questions

  • What is Dependency Injection in .NET 9?
  • Difference between Factory and Strategy?
  • Why Repository pattern is used?
  • What problems does Singleton solve?
  • How does DI improve testability?

Conclusion

Design patterns in .NET 9 are essential for building:

  • Scalable systems
  • Maintainable codebases
  • Enterprise-level applications

Mastering these patterns will:

  • Boost your coding skills
  • Help in interviews
  • Make you think like a senior developer

Best and Most Recommended ASP.NET Core 10.0 Hosting

Fortunately, there are a number of dependable and recommended web hosts available that can help you gain control of your website’s performance and improve your ASP.NET Core 10.0 web ranking. HostForLIFE.eu is highly recommended. In Europe, HostForLIFE.eu is the most popular option for first-time web hosts searching for an affordable plan. Their standard price begins at only €3.49 per month. Customers are permitted to choose quarterly and annual plans based on their preferences. HostForLIFE.eu guarantees “No Hidden Fees” and an industry-leading ’30 Days Cash Back’ policy. Customers who terminate their service within the first thirty days are eligible for a full refund.

By providing reseller hosting accounts, HostForLIFE.eu also gives its consumers the chance to generate income. You can purchase their reseller hosting account, host an unlimited number of websites on it, and even sell some of your hosting space to others. This is one of the most effective methods for making money online. They will take care of all your customers’ hosting needs, so you do not need to fret about hosting-related matters.