Skip to content
FullstackCodingGuy edited this page Feb 24, 2025 · 16 revisions

Conditionally Applying Decorators in .NET Dependency Injection?

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();

How to register multiple implementations for the same interface and resolve it?

read

Use of Decorator Pattern

Approach 1

image image image

Approach 2

image

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

image image

References

Clone this wiki locally