-
-
Notifications
You must be signed in to change notification settings - Fork 1
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.
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");
}
}
Decorators are automatically applied when you call .Register()
builder.Services
.AddAutowiringForAssembly(Assembly.GetExecutingAssembly())
.Register();
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
}