Repository navigation
OnixLabs.DependencyInjection.IServiceCollectionExtensions
Provides extension methods for IServiceCollection instances that register services with a configurable ServiceLifetime, selected at the call site rather than by which method you call.
| Namespace | OnixLabs.DependencyInjection |
| Assembly | OnixLabs.DependencyInjection.dll (NuGet) |
| Inheritance |
object → IServiceCollectionExtensions
|
[EditorBrowsable(EditorBrowsableState.Never)]
public static class IServiceCollectionExtensions
{
extension(IServiceCollection services)
{
// AddService / AddKeyedService members
}
}Microsoft's built-in registration API exposes the service lifetime through the method name — AddSingleton, AddScoped, and AddTransient are three distinct methods. This couples the lifetime decision to the call site syntactically, which is awkward when the lifetime is itself a value: configuration-driven, passed as a parameter, or chosen by a loop over many registrations.
IServiceCollectionExtensions collapses each of those method triples into a single method that takes a ServiceLifetime argument. Each method dispatches on that argument to the corresponding built-in Microsoft.Extensions.DependencyInjection registration method, so behaviour is identical to calling the framework method directly — only the selection mechanism differs.
The container class is decorated with [EditorBrowsable(EditorBrowsableState.Never)], which keeps the class itself out of IntelliSense lists while its extension methods remain fully usable on the receiver. The members are declared inside a C# 14 extension block (extension(IServiceCollection services) { ... }), so the receiver appears in the block declaration rather than as a this parameter. The signatures shown below are the call-site signatures as consumed by user code. Bring the methods into scope with using OnixLabs.DependencyInjection;.
Key behaviours:
-
Three registration shapes, mirrored as keyed and unkeyed. Each of
AddServiceandAddKeyedServiceis overloaded to register: a concrete type (TService); a service type with a separate implementation type (TService, TImplementationor a non-genericType, Typepair); or an implementation factory delegate. The keyed overloads additionally take aserviceKeyand forward to theAddKeyed…family. -
Default lifetime. The
lifetimeparameter defaults todefault, which forServiceLifetimeisServiceLifetime.Singleton(the enum's zero value). Omittinglifetimetherefore registers a singleton. -
Lifetime validation. Every method validates
lifetimewithRequireIsDefinedbefore dispatching, throwingArgumentOutOfRangeExceptionwhen the value is not one ofSingleton,Scoped, orTransient. This guards against an out-of-range cast such as(ServiceLifetime)int.MaxValue. -
Fluent return. Every method returns the same
IServiceCollectioninstance, so registrations can be chained.
The motivating case: the lifetime is decided by data rather than by which method you call.
using Microsoft.Extensions.DependencyInjection;
using OnixLabs.DependencyInjection;
ServiceLifetime lifetime = configuration.GetValue<ServiceLifetime>("Repository:Lifetime");
services.AddService<IRepository, SqlRepository>(lifetime);// Both register IClock -> SystemClock as a singleton.
services.AddService<IClock, SystemClock>();
services.AddService<IClock, SystemClock>(ServiceLifetime.Singleton);// Factory-based registration.
services.AddService<IConnection>(provider =>
new Connection(provider.GetRequiredService<IOptions<DbOptions>>().Value), ServiceLifetime.Scoped);
// Keyed registration, resolved later with [FromKeyedServices("primary")].
services.AddKeyedService<ICache, RedisCache>("primary", ServiceLifetime.Singleton);Useful when the service and implementation types are discovered by reflection (for example, convention-based registration).
foreach ((Type service, Type implementation) in DiscoverHandlers())
{
services.AddService(service, implementation, ServiceLifetime.Transient);
}All members are extension methods on IServiceCollection and return the same instance. Each maps to the corresponding Microsoft.Extensions.DependencyInjection registration method for the supplied ServiceLifetime.
| Method | Returns | Description |
|---|---|---|
AddService<TService>(ServiceLifetime) |
IServiceCollection |
Registers the concrete service type TService. |
AddService<TService, TImplementation>(ServiceLifetime) |
IServiceCollection |
Registers TService with implementation type TImplementation. |
AddService<TService>(Func<IServiceProvider, TService>, ServiceLifetime) |
IServiceCollection |
Registers TService using an implementation factory. |
AddService(Type, Type, ServiceLifetime) |
IServiceCollection |
Registers a service type with an implementation type, by runtime Type. |
| Method | Returns | Description |
|---|---|---|
AddKeyedService<TService>(object?, ServiceLifetime) |
IServiceCollection |
Registers the concrete service type TService against a service key. |
AddKeyedService<TService, TImplementation>(object?, ServiceLifetime) |
IServiceCollection |
Registers TService with implementation TImplementation against a service key. |
AddKeyedService<TService>(Func<IServiceProvider, object?, TService>, object?, ServiceLifetime) |
IServiceCollection |
Registers TService against a service key, using a keyed implementation factory. |
AddKeyedService(Type, Type, object?, ServiceLifetime) |
IServiceCollection |
Registers a service type with an implementation type against a service key, by runtime Type. |
public IServiceCollection AddService<TService>(ServiceLifetime lifetime = default)
where TService : classAdds a service of the type specified in TService to the current IServiceCollection. Dispatches to AddSingleton<TService>, AddScoped<TService>, or AddTransient<TService> according to lifetime.
| Parameter | Type | Description |
|---|---|---|
lifetime |
ServiceLifetime |
The lifetime of the TService service. Defaults to ServiceLifetime.Singleton. |
| Type Parameter | Description |
|---|---|
TService |
The underlying type of the service to add. Must be a reference type. |
Returns — The current IServiceCollection instance, after the service has been registered.
Exceptions
| Exception | Condition |
|---|---|
ArgumentOutOfRangeException |
lifetime is not a defined ServiceLifetime member. |
services.AddService<SystemClock>(ServiceLifetime.Singleton);public IServiceCollection AddService<TService, TImplementation>(ServiceLifetime lifetime = default)
where TImplementation : class, TService
where TService : classAdds a service of the type specified in TService with an implementation type specified in TImplementation to the current IServiceCollection. Dispatches to AddSingleton<TService, TImplementation>, AddScoped<TService, TImplementation>, or AddTransient<TService, TImplementation> according to lifetime.
| Parameter | Type | Description |
|---|---|---|
lifetime |
ServiceLifetime |
The lifetime of the TService service. Defaults to ServiceLifetime.Singleton. |
| Type Parameter | Description |
|---|---|
TService |
The type of the service to add. Must be a reference type. |
TImplementation |
The type of the implementation to use. Must be a reference type assignable to TService. |
Returns — The current IServiceCollection instance, after the service has been registered.
Exceptions
| Exception | Condition |
|---|---|
ArgumentOutOfRangeException |
lifetime is not a defined ServiceLifetime member. |
services.AddService<IRepository, SqlRepository>(ServiceLifetime.Scoped);public IServiceCollection AddService<TService>(
Func<IServiceProvider, TService> implementationFactory,
ServiceLifetime lifetime = default)
where TService : classAdds a service of the type specified in TService to the current IServiceCollection, using a factory to create the service. Dispatches to AddSingleton, AddScoped, or AddTransient according to lifetime.
| Parameter | Type | Description |
|---|---|---|
implementationFactory |
Func<IServiceProvider, TService> |
The factory that creates the service from the resolved IServiceProvider. |
lifetime |
ServiceLifetime |
The lifetime of the TService service. Defaults to ServiceLifetime.Singleton. |
| Type Parameter | Description |
|---|---|
TService |
The underlying type of the service to add. Must be a reference type. |
Returns — The current IServiceCollection instance, after the service has been registered.
Exceptions
| Exception | Condition |
|---|---|
ArgumentOutOfRangeException |
lifetime is not a defined ServiceLifetime member. |
services.AddService<IConnection>(provider => new Connection(provider.GetRequiredService<DbOptions>()), ServiceLifetime.Scoped);public IServiceCollection AddService(
Type serviceType,
Type implementationType,
ServiceLifetime lifetime = default)Adds a service of the type specified in serviceType with an implementation of the type specified in implementationType to the current IServiceCollection. This non-generic overload is suited to registrations driven by reflection. Dispatches to AddSingleton, AddScoped, or AddTransient according to lifetime.
| Parameter | Type | Description |
|---|---|---|
serviceType |
Type |
The type of the service to register. |
implementationType |
Type |
The implementation type of the service. |
lifetime |
ServiceLifetime |
The lifetime of the service. Defaults to ServiceLifetime.Singleton. |
Returns — The current IServiceCollection instance, after the service has been registered.
Exceptions
| Exception | Condition |
|---|---|
ArgumentOutOfRangeException |
lifetime is not a defined ServiceLifetime member. |
services.AddService(typeof(IRepository), typeof(SqlRepository), ServiceLifetime.Transient);public IServiceCollection AddKeyedService<TService>(
object? serviceKey,
ServiceLifetime lifetime = default)
where TService : classAdds a keyed service of the type specified in TService to the current IServiceCollection. Dispatches to AddKeyedSingleton<TService>, AddKeyedScoped<TService>, or AddKeyedTransient<TService> according to lifetime.
| Parameter | Type | Description |
|---|---|---|
serviceKey |
object? |
The ServiceDescriptor.ServiceKey of the service. May be null. |
lifetime |
ServiceLifetime |
The lifetime of the TService service. Defaults to ServiceLifetime.Singleton. |
| Type Parameter | Description |
|---|---|
TService |
The underlying type of the service to add. Must be a reference type. |
Returns — The current IServiceCollection instance, after the service has been registered.
Exceptions
| Exception | Condition |
|---|---|
ArgumentOutOfRangeException |
lifetime is not a defined ServiceLifetime member. |
services.AddKeyedService<RedisCache>("primary", ServiceLifetime.Singleton);public IServiceCollection AddKeyedService<TService, TImplementation>(
object? serviceKey,
ServiceLifetime lifetime = default)
where TImplementation : class, TService
where TService : classAdds a keyed service of the type specified in TService with an implementation type specified in TImplementation to the current IServiceCollection. Dispatches to AddKeyedSingleton<TService, TImplementation>, AddKeyedScoped<TService, TImplementation>, or AddKeyedTransient<TService, TImplementation> according to lifetime.
| Parameter | Type | Description |
|---|---|---|
serviceKey |
object? |
The ServiceDescriptor.ServiceKey of the service. May be null. |
lifetime |
ServiceLifetime |
The lifetime of the TService service. Defaults to ServiceLifetime.Singleton. |
| Type Parameter | Description |
|---|---|
TService |
The type of the service to add. Must be a reference type. |
TImplementation |
The type of the implementation to use. Must be a reference type assignable to TService. |
Returns — The current IServiceCollection instance, after the service has been registered.
Exceptions
| Exception | Condition |
|---|---|
ArgumentOutOfRangeException |
lifetime is not a defined ServiceLifetime member. |
services.AddKeyedService<ICache, RedisCache>("primary", ServiceLifetime.Scoped);public IServiceCollection AddKeyedService<TService>(
Func<IServiceProvider, object?, TService> implementationFactory,
object? serviceKey,
ServiceLifetime lifetime = default)
where TService : classAdds a keyed service of the type specified in TService to the current IServiceCollection, using a factory to create the service. The factory receives both the resolved IServiceProvider and the serviceKey. Dispatches to AddKeyedSingleton, AddKeyedScoped, or AddKeyedTransient according to lifetime.
| Parameter | Type | Description |
|---|---|---|
implementationFactory |
Func<IServiceProvider, object?, TService> |
The factory that creates the service from the resolved IServiceProvider and the service key. |
serviceKey |
object? |
The ServiceDescriptor.ServiceKey of the service. May be null. |
lifetime |
ServiceLifetime |
The lifetime of the TService service. Defaults to ServiceLifetime.Singleton. |
| Type Parameter | Description |
|---|---|
TService |
The underlying type of the service to add. Must be a reference type. |
Returns — The current IServiceCollection instance, after the service has been registered.
Exceptions
| Exception | Condition |
|---|---|
ArgumentOutOfRangeException |
lifetime is not a defined ServiceLifetime member. |
services.AddKeyedService<ICache>((provider, key) => new RedisCache((string)key!), "primary", ServiceLifetime.Singleton);public IServiceCollection AddKeyedService(
Type serviceType,
Type implementationType,
object? serviceKey,
ServiceLifetime lifetime = default)Adds a keyed service of the type specified in serviceType with an implementation of the type specified in implementationType to the current IServiceCollection. This non-generic overload is suited to registrations driven by reflection. Dispatches to AddKeyedSingleton, AddKeyedScoped, or AddKeyedTransient according to lifetime.
| Parameter | Type | Description |
|---|---|---|
serviceType |
Type |
The type of the service to register. |
implementationType |
Type |
The implementation type of the service. |
serviceKey |
object? |
The ServiceDescriptor.ServiceKey of the service. May be null. |
lifetime |
ServiceLifetime |
The lifetime of the service. Defaults to ServiceLifetime.Singleton. |
Returns — The current IServiceCollection instance, after the service has been registered.
Exceptions
| Exception | Condition |
|---|---|
ArgumentOutOfRangeException |
lifetime is not a defined ServiceLifetime member. |
services.AddKeyedService(typeof(IRepository), typeof(SqlRepository), "primary", ServiceLifetime.Transient);ONIXLabs .NET Library · Repository · NuGet · License (Apache-2.0)
Copyright © ONIXLabs 2020. Licensed under the Apache License, Version 2.0.
- Enumeration<T>
- Optional<T>
- OptionalEqualityComparer<T>
- OptionalExtensions
- Result
- Result<T>
- ResultEqualityComparer<T>
- ResultExtensions
- Specification<T>
- Preconditions
- IValueEquatable<T>
- IValueComparable<T>
- IBinaryConvertible
- ISpanBinaryConvertible
- IMemoryBinaryConvertible
- ArrayExtensions
- ComparableExtensions
- DateTimeExtensions
- ISpanParsableExtensions
- ObjectExtensions
- RandomExtensions
- ReadOnlySequenceExtensions
- ReadOnlySpanExtensions
- StringExtensions
- Base16
- Base32
- Base58
- Base64
- IBaseCodec
- IBaseValue
- IBaseValue<T>
- Base16Codec
- Base32Codec
- Base58Codec
- Base64Codec
- Base16FormatProvider
- Base32FormatProvider
- Base58FormatProvider
- Base64FormatProvider
- EncodingExtensions
- ReadOnlySpanExtensions
- StringBuilderExtensions
- BigDecimal
- BigDecimalEqualityComparer
- BigDecimalOrdinalityComparer
- NumberInfo
- NumberInfoEqualityComparer
- NumberInfoOrdinalityComparer
- Int256
- Int512
- UInt256
- UInt512
- Float128
- Float256
- GenericMath
- NumericsExtensions
- ConversionMode
- ScaleMode
- Hash
- NamedHash
- Sha3
- Sha3Hash224
- Sha3Hash256
- Sha3Hash384
- Sha3Hash512
- Sha3Shake128
- Sha3Shake256
- MerkleTree
- MerkleTree<T>
- PrivateKey
- PublicKey
- NamedPrivateKey
- NamedPublicKey
- EcdhPrivateKey
- EcdhPublicKey
- EcdsaPrivateKey
- EcdsaPublicKey
- EddsaPrivateKey
- EddsaPublicKey
- RsaPrivateKey
- RsaPublicKey
- DigitalSignature
- DigitalSignatureAndPublicKey
- Salt
- Secret
- ICryptoPrimitive<T>
- IHashable
- IEcdhPrivateKey
- IEcdsaPrivateKey
- IEddsaPrivateKey
- IRsaPrivateKey
- IPrivateKeyDerivable<T>
- IPrivateKeyExportable
- IPrivateKeyImportable<T>
- IPrivateKeyPemImportable<T>
- IPrivateKeyPkcs8Exportable
- IPrivateKeyPkcs8Importable<T>
- IPrivateKeyPkcs8PemExportable
- IPrivateKeyRawExportable
- IPrivateKeyRawImportable<T>
- IPrivateKeyRawPemExportable
- IEcdhPublicKey
- IEcdsaPublicKey
- IEddsaPublicKey
- IRsaPublicKey
- IPublicKeyExportable
- IPublicKeyImportable<T>
- IPublicKeyPemExportable
- IPublicKeyPemImportable<T>
- IPublicKeyRawExportable
- IPublicKeyRawImportable<T>
- HashAlgorithmExtensions
- ReadOnlySpanExtensions