CSharpEssentials.DependencyInjection
Attribute-based service registration with a source-generated registry that scans nothing at startup (trim and Native AOT safe), plus decorators.
Installation
dotnet add package CSharpEssentials.DependencyInjection
Target frameworks: net11.0, net10.0, net9.0, net8.0, netstandard2.1. The generic attribute forms ([RegisterScoped<TService>], [Decorates<TService>]) need net7.0 or later; on netstandard2.1 use the typeof(...) forms. The generator, analyzer and code fix ship in the package.
Namespace
using CSharpEssentials.DependencyInjection;
Registering services
[RegisterScoped] // IOrderService, by the I{TypeName} rule
public sealed class OrderService : IOrderService { }
[RegisterSingleton(typeof(IClock))] // explicit service type
public sealed class SystemClock : IClock { }
[RegisterSingleton<IPaymentGateway>(Key = "card")] // generic form, keyed
public sealed class CardGateway : IPaymentGateway { }
[RegisterTransient(typeof(IRepository<>))] // open generic
public sealed class Repository<T> : IRepository<T> { }
[RegisterScoped(As = ServiceAs.SelfWithInterfaces, Strategy = RegistrationStrategy.TryAdd)]
public sealed class ReportBuilder : IDisposable { public void Dispose() { } }
Without a service type and without As, a class registers as its interface named I{TypeName} (same generic arity), otherwise as itself.
| Property | Values |
|---|---|
| Key | Any attribute constant. null = non-keyed. |
| As | Self, SelfWithInterfaces (interfaces forward to one shared instance), ImplementedInterfaces |
| Strategy | Add (default), TryAdd, TryAddEnumerable, Replace, Throw. All are key-aware. |
[ExcludeFromRegistration]on a class or an assembly opts out.- With
Add, a generated registration and a manualAddScoped<IOrderService, OrderService>()both stay:GetService<T>()resolves the last one,GetServices<T>()returns both. UseTryAddorThrowwhen that is not wanted.
Decorators
[Decorates(typeof(IOrderService), Order = 1)]
public sealed class LoggingOrderService(IOrderService inner, ILogger<LoggingOrderService> logger) : IOrderService { }
Or at runtime:
services.Decorate<IOrderService, LoggingOrderService>(); // throws InvalidOperationException when nothing matches
services.Decorate<IPaymentGateway, RetryingGateway>(serviceKey: "card");
services.Decorate<IClock>((inner, sp) => new CachedClock(inner));
services.TryDecorate<IOrderService, AuditingOrderService>(); // returns false when nothing matches
services.Decorate(typeof(IRepository<>), typeof(CachedRepository<>)); // decorates closed registrations such as IRepository<Order>
Decorate(Type, Type)throwsInvalidOperationExceptionwhen a registration of the open generic type itself exists or no closed registration matches; it is[RequiresUnreferencedCode]/[RequiresDynamicCode].- Attribute decorators apply in ascending
Order. Every matching registration is decorated; the decorator keeps its lifetime and key. - The original moves to a hidden private key under a service type other than
Tandobject, so it never shows up inGetServices<T>(),GetKeyedServices<T>(KeyedService.AnyKey)orGetKeyedServices<object>(KeyedService.AnyKey). The hidden inner of a scoped service is transient, resolved once per cached decorator. The container disposes both. - An original implementation that injects
[ServiceKey]cannot be decorated (InvalidOperationException). - A decorator needs exactly one public constructor with exactly one parameter of the decorated type.
- Other decorator parameters:
[ServiceKey]gets the decorated key;[FromKeyedServices("k")]resolves keyk,[FromKeyedServices(null)]the non-keyed registration, and parameterless[FromKeyedServices](.NET 10) inherits the decorated key.
Generated registry
Each assembly with marked classes gets services.Add{Assembly}Services() (dots removed: Sample.Billing → AddSampleBillingServices()), plus an overload taking an ILogger that logs duplicate (service, key) registrations at Debug. It registers the assembly's services, then applies its decorators immediately, so a decorator of a service registered by another assembly throws InvalidOperationException unless that assembly's Add{Assembly}Services() (or a manual registration) ran first.
Applications (Exe/WinExe, not test projects) also get an internal AddAllServices(), which registers every referenced assembly's registry and the app's own before applying any decorator, so a decorator can wrap a service from another assembly. Order is global across assemblies; ties follow assembly order (referenced by name, the app last), then type name. AddServicesFromAssemblies does the same with the assemblies in the order passed.
Registration is idempotent per assembly: Add{Assembly}Services, AddAllServices and AddServicesFromAssemblies skip assemblies already registered by any of them. The per-assembly marker is written only after registrations and decorators succeed, so a failed call can be retried, but not cleanly: descriptors added before the exception stay, and AddAllServices leaves the successful registries unmarked too. Fix the cause and build a new collection. The marker is a singleton ServiceDescriptor of an internal type that counts in services.Count, so account for it when asserting descriptor counts.
| Assembly attribute | Effect |
|---|---|
| [assembly: ServiceRegistryName("Billing")] | Names the method AddBillingServices() |
| [assembly: GenerateServiceAggregate] | Generates AddAllServices() in a library or test project |
| [assembly: DisableServiceAggregate] | Turns off AddAllServices() in an application |
Reflection fallback
For assemblies that cannot use the generator (plugins loaded at runtime):
services.AddServicesFromAssemblies(typeof(OrderService).Assembly);
Marked [RequiresUnreferencedCode] and [RequiresDynamicCode]; prefer the generated method in trimmed and AOT apps. Without a logger, unloadable types throw; the overload taking an ILogger first warns and continues.
Diagnostics
| ID | Severity | Rule |
|---|---|---|
| CSE2001 | Error | Class does not implement the service type |
| CSE2002 | Error | A RegistrationStrategy.Throw registration whose service and key an earlier registration in the same assembly already registers (types in metadata name order) |
| CSE2003 | Info | Class has interfaces but none matches I{TypeName}, so it registers as itself. Code fix adds typeof(IFoo) or As = ServiceAs.Self |
| CSE2004 | Error | Decorator has zero or several constructor parameters of the decorated type |
| CSE2005 | Error | Decorator does not have exactly one public constructor |
| CSE2006 | Info | Captive dependency: a singleton takes a scoped/transient service (or scoped takes transient) registered by attribute in the same project |
| CSE2007 | Error | Class cannot be constructed by generated code (abstract, static, file-local, inaccessible, nested in a generic type) |
| CSE2008 | Warning | Open-generic decorators are not generated; call services.Decorate(typeof(IRepository<>), typeof(CachedRepository<>)) at runtime (closed registrations only) |
| CSE2009 | Warning | Two referenced assemblies produce the same registry name (Foo.Api and FooApi → FooApiServiceRegistry); AddAllServices skips both until one sets [assembly: ServiceRegistryName("...")]. Also reported when the project's own registry has the same name as a referenced one; only the own registry is called |
Migrating from Scrutor
| Scrutor | CSharpEssentials.DependencyInjection |
|---|---|
| services.Scan(s => s.FromAssemblyOf<T>().AddClasses(...)) | [RegisterScoped]/[RegisterSingleton]/[RegisterTransient] on each class, then services.Add{Assembly}Services() |
| .AsMatchingInterface() | Default I{TypeName} rule |
| .As<IFoo>() | [RegisterScoped(typeof(IFoo))] or [RegisterScoped<IFoo>] |
| .AsSelf() / .AsSelfWithInterfaces() / .AsImplementedInterfaces() | As = ServiceAs.Self / SelfWithInterfaces / ImplementedInterfaces |
| .WithScopedLifetime() | The attribute name carries the lifetime |
| RegistrationStrategy.Append / Skip / Replace() / Throw | Strategy = RegistrationStrategy.Add / TryAdd / Replace / Throw |
| Decorate / TryDecorate | Same calls (also keyed), or [Decorates(typeof(IFoo))] |
| .FromApplicationDependencies() | AddAllServices() |
| Namespace or type filters | [ExcludeFromRegistration] |
Build after adding attributes: CSE2003 flags classes whose interfaces do not follow I{TypeName}. Remove Scrutor afterwards; both define Decorate/TryDecorate in Microsoft.Extensions.DependencyInjection, so calls are ambiguous while both are referenced.
Best practices
- Prefer the generated
Add{Assembly}Services()/AddAllServices()overAddServicesFromAssemblies. - When decorators wrap services from other assemblies, call
AddAllServices(), or call the per-assembly methods with dependencies first. - Use
Strategy = RegistrationStrategy.ThroworTryAddfor services that must have one registration. - Treat CSE2006 (captive dependency) as a bug even though it is Info.
- Add a unit test that groups
IServiceCollectionby(ServiceType, ServiceKey)to catch unintended duplicates.