Skip to content

RegisterOnInherit

Scans assemblies for non-abstract, non-interface types assignable to T and registers each discovered type in the service collection. This is useful for command handlers, job classes, plugin-style modules, and other patterns where implementations should be discovered from assemblies.

There are two overloads. The simpler overload registers each discovered implementation as T, which is useful when consumers resolve IEnumerable<T> or a known base contract. The overload with addType lets callers choose whether registrations use service type T or the concrete type itself.

Usage

csharp
using System.Reflection;
using AlmightyShogun.Utils;
using Microsoft.Extensions.DependencyInjection;

builder.Services.RegisterOnInherit<ICommandHandler>(
    ServiceLifetime.Transient,
    Assembly.GetExecutingAssembly()
);
csharp
using System.Reflection;
using AlmightyShogun.Utils;
using Microsoft.Extensions.DependencyInjection;

builder.Services.RegisterOnInherit<ICommandHandler>(
    false,
    ServiceLifetime.Transient,
    Assembly.GetExecutingAssembly()
);
csharp
public interface ICommandHandler
{
    Task HandleAsync();
}

public sealed class ImportCommandHandler : ICommandHandler
{
    public Task HandleAsync()
    {
        Console.WriteLine("Import started.");

        return Task.CompletedTask;
    }
}

Parameters

serviceLifetime: ServiceLifetime
Lifetime used for every discovered registration.
Default: ServiceLifetime.Singleton

assemblies: Assembly[]
Assemblies to scan. When omitted, the calling assembly is scanned.
Default: []

addType: bool
Whether discovered implementations should be registered as service type T instead of their concrete type.

Returns

The IServiceCollection instance with discovered concrete types registered.

Type signature

csharp
public IServiceCollection RegisterOnInherit<T>(
    ServiceLifetime serviceLifetime = ServiceLifetime.Singleton,
    params Assembly[] assemblies
) where T : class;

public IServiceCollection RegisterOnInherit<T>(
    bool addType,
    ServiceLifetime serviceLifetime = ServiceLifetime.Singleton,
    params Assembly[] assemblies
) where T : class;

Uses

All packages are released under the MIT License.