Design patterns in .NET are proven, reusable solutions to common software design problems. They provide structured approaches for organizing code, improving maintainability, enhancing scalability, and promoting best practices in enterprise application development. In C# and ASP.NET Core applications, design patterns help developers build loosely coupled, testable, and extensible systems that align with modern architectural standards.
Design patterns are typically categorized into three major groups: Creational, Structural, and Behavioral patterns.
Creational Design Patterns in .NET
Creational patterns focus on object creation mechanisms, ensuring flexibility and reuse.
1. Singleton Pattern
The Singleton pattern ensures that a class has only one instance and provides a global point of access to it.
Real-world example in .NET:
Logging service
Configuration manager
Caching service
Example:
public sealed class Logger
{
private static readonly Logger _instance = new Logger();
private Logger() { }
public static Logger Instance => _instance;
public void Log(string message)
{
Console.WriteLine(message);
}
}
In ASP.NET Core, dependency injection often replaces manual Singleton implementations.
2. Factory Pattern
The Factory pattern creates objects without exposing the instantiation logic to the client.
Real-world example:
Payment gateway selection (CreditCard, UPI, PayPal)
Notification services (Email, SMS, Push)
Example:
public interface IPayment
{
void Process();
}
public class CreditCardPayment : IPayment
{
public void Process() => Console.WriteLine("Processing credit card payment");
}
public class PaymentFactory
{
public static IPayment Create(string type)
{
return type switch
{
"CreditCard" => new CreditCardPayment(),
_ => throw new ArgumentException("Invalid type")
};
}
}
Factories improve extensibility and reduce tight coupling.
3. Dependency Injection Pattern
Dependency Injection (DI) promotes loose coupling by injecting dependencies instead of creating them directly.
Real-world example:
Injecting repository into service
Injecting logger into controller
ASP.NET Core has built-in support for dependency injection through the IServiceCollection container.
Structural Design Patterns in .NET
Structural patterns focus on organizing classes and objects to form larger structures.
4. Repository Pattern
The Repository pattern abstracts data access logic from business logic.
Real-world example:
Separating Entity Framework Core queries from service layer
Example:
Join the conversation! Your thoughts help the community grow.