Skip to content

04. Decorators

Tim Maes edited this page Oct 15, 2024 · 1 revision

Decorators allow you to add additional behavior to existing services without modifying their implementations.

Defining a decorator

Decorate your calss with [RegisterDecorator] and specify the type it decorates.

[RegisterDecorator(typeof(IMyService))]
public class LoggingDecorator : IMyService
{
    private readonly IMyService _innerService;

    public LoggingDecorator(IMyService innerService)
    {
        _innerService = innerService;
    }

    public void DoSomething()
    {
        Console.WriteLine("Before execution");
        _innerService.DoSomething();
        Console.WriteLine("After execution");
    }
}

Applying Decorators

Decorators are automatically applied when you call .Register()

builder.Services
    .AddAutowiringForAssembly(Assembly.GetExecutingAssembly())
    .Register();

Decorator Orders

You can specify the order in which decorators are applied using the Order parameters.

[RegisterDecorator(typeof(IMyService), Order = 1)]
public class FirstDecorator : IMyService
{
    // Implementation
}

[RegisterDecorator(typeof(IMyService), Order = 2)]
public class SecondDecorator : IMyService
{
    // Implementation
}
Clone this wiki locally