-
Notifications
You must be signed in to change notification settings - Fork 0
.NET
FullstackCodingGuy edited this page Feb 24, 2025
·
16 revisions
read
In .NET DI, you can conditionally apply the Decorator Pattern based on configuration or runtime conditions using IServiceCollection.
public class LoggingExpenseServiceDecorator : IExpenseService
{
private readonly IExpenseService _inner;
private readonly ILogger<LoggingExpenseServiceDecorator> _logger;
`public LoggingExpenseServiceDecorator(IExpenseService inner, ILogger<LoggingExpenseServiceDecorator> logger)`
`{`
`_inner = inner;`
`_logger = logger;`
`}`
`public async Task<string> ProcessExpenseAsync(decimal amount)`
`{`
`_logger.LogInformation($"Processing expense: {amount} USD");`
`var result = await _inner.ProcessExpenseAsync(amount);`
`_logger.LogInformation($"Expense processed successfully: {result}");`
`return result;`
`}`
}
In Program.cs
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
// Register the base service
services.AddScoped<IExpenseService, ExpenseService>();
// Conditionally apply the decorator
bool useLoggingDecorator = builder.Configuration.GetValue<bool>("UseLoggingDecorator");
if (useLoggingDecorator)
{
services.AddScoped<IExpenseService>(provider =>
{
var innerService = provider.GetRequiredService<ExpenseService>();
var logger = provider.GetRequiredService<ILogger<LoggingExpenseServiceDecorator>>();
return new LoggingExpenseServiceDecorator(innerService, logger);
});
}
var app = builder.Build();
read
- https://timdeschryver.dev/blog/the-decorator-pattern-using-nets-dependency-injection
- https://medium.com/@anderson.buenogod/mastering-the-decorator-pattern-in-c-net-8-advanced-use-cases-and-best-practices-378974abe9be
Approach 1



Approach 2

Approach 3 - Using Keyed Services to Register Multiple Implementations of the Same Interface

