Skip to content

OnixLabs.DependencyInjection.IServiceCollectionExtensions

matthew edited this page May 27, 2026 · 2 revisions

IServiceCollectionExtensions Class

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

Definition

[EditorBrowsable(EditorBrowsableState.Never)]
public static class IServiceCollectionExtensions
{
    extension(IServiceCollection services)
    {
        // AddService / AddKeyedService members
    }
}

Remarks

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 AddService and AddKeyedService is overloaded to register: a concrete type (TService); a service type with a separate implementation type (TService, TImplementation or a non-generic Type, Type pair); or an implementation factory delegate. The keyed overloads additionally take a serviceKey and forward to the AddKeyed… family.
  • Default lifetime. The lifetime parameter defaults to default, which for ServiceLifetime is ServiceLifetime.Singleton (the enum's zero value). Omitting lifetime therefore registers a singleton.
  • Lifetime validation. Every method validates lifetime with RequireIsDefined before dispatching, throwing ArgumentOutOfRangeException when the value is not one of Singleton, Scoped, or Transient. This guards against an out-of-range cast such as (ServiceLifetime)int.MaxValue.
  • Fluent return. Every method returns the same IServiceCollection instance, so registrations can be chained.

Examples

Registering with a configuration-driven lifetime

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);

Defaulting to a singleton

// Both register IClock -> SystemClock as a singleton.
services.AddService<IClock, SystemClock>();
services.AddService<IClock, SystemClock>(ServiceLifetime.Singleton);

Registering a factory and a keyed service

// 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);

Registering by runtime Type

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);
}

Methods

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.

Unkeyed services

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.

Keyed services

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.

AddService<TService>(ServiceLifetime)

public IServiceCollection AddService<TService>(ServiceLifetime lifetime = default)
    where TService : class

Adds 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);

AddService<TService, TImplementation>(ServiceLifetime)

public IServiceCollection AddService<TService, TImplementation>(ServiceLifetime lifetime = default)
    where TImplementation : class, TService
    where TService : class

Adds 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);

AddService<TService>(Func<IServiceProvider, TService>, ServiceLifetime)

public IServiceCollection AddService<TService>(
    Func<IServiceProvider, TService> implementationFactory,
    ServiceLifetime lifetime = default)
    where TService : class

Adds 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);

AddService(Type, Type, ServiceLifetime)

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);

AddKeyedService<TService>(object?, ServiceLifetime)

public IServiceCollection AddKeyedService<TService>(
    object? serviceKey,
    ServiceLifetime lifetime = default)
    where TService : class

Adds 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);

AddKeyedService<TService, TImplementation>(object?, ServiceLifetime)

public IServiceCollection AddKeyedService<TService, TImplementation>(
    object? serviceKey,
    ServiceLifetime lifetime = default)
    where TImplementation : class, TService
    where TService : class

Adds 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);

AddKeyedService<TService>(Func<IServiceProvider, object?, TService>, object?, ServiceLifetime)

public IServiceCollection AddKeyedService<TService>(
    Func<IServiceProvider, object?, TService> implementationFactory,
    object? serviceKey,
    ServiceLifetime lifetime = default)
    where TService : class

Adds 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);

AddKeyedService(Type, Type, object?, ServiceLifetime)

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);

See Also

ONIXLabs .NET Library


Clone this wiki locally