DecoratorForAttribute TService
NexusLabs.Needlr¶
NexusLabs.Needlr¶
DecoratorForAttribute<TService> Class¶
Marks a class as a decorator for the specified service type. When discovered by Needlr (via source generation or reflection), the decorator will be automatically wired using AddDecorator<TService,TDecorator>(this IServiceCollection).
Type parameters¶
TService
The service type (interface or class) that this class decorates.
Inheritance System.Object 🡒 System.Attribute 🡒 DecoratorForAttribute\<TService>
Example¶
public interface IMyService
{
string GetValue();
}
public class MyService : IMyService
{
public string GetValue() => "Original";
}
[DecoratorFor<IMyService>(Order = 1)]
public class LoggingDecorator : IMyService
{
private readonly IMyService _inner;
public LoggingDecorator(IMyService inner) => _inner = inner;
public string GetValue()
{
Console.WriteLine("Before");
var result = _inner.GetValue();
Console.WriteLine("After");
return result;
}
}
[DecoratorFor<IMyService>(Order = 2)]
public class CachingDecorator : IMyService
{
private readonly IMyService _inner;
private string? _cached;
public CachingDecorator(IMyService inner) => _inner = inner;
public string GetValue() => _cached ??= _inner.GetValue();
}
Remarks¶
The decorated class must implement TService and accept an instance of TService in its constructor.
When multiple decorators exist for the same service, use the Order property to control the decoration order. Lower values are applied first (closer to the original service), higher values wrap outer layers.
Using this attribute implicitly excludes the type from normal interface registration (equivalent to applying DoNotAutoRegisterAttribute for the decorated interface).
Properties¶
DecoratorForAttribute<TService>.Order Property¶
Gets or sets the order in which this decorator is applied relative to other decorators for the same service. Lower values are applied first (closer to the original implementation). Default is 0.
Property Value¶
Remarks¶
Example with Order values: - Original service: MyService - Order = 1: LoggingDecorator wraps MyService - Order = 2: CachingDecorator wraps LoggingDecorator
Resolving IMyService returns: CachingDecorator → LoggingDecorator → MyService
DecoratorForAttribute<TService>.ServiceType Property¶
Gets the service type that this decorator wraps.