Dependency injection: register all classes that implement a specific interface

You can register all classes in a project (or folder) that implement a certain interface. See the code below how to do this.

using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder();

var type = typeof(IBootstrap);
var types = System.AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(x => x.GetTypes())
    .Where(p => type.IsAssignableFrom(p) && p.IsClass);

foreach (var p in types)
{
    var config = (IBootstrap)System.Activator.CreateInstance(p)!;
    config.Register(builder.Services);
}

var app = builder.Build();

app.Run(context =>
{
    var person = context.RequestServices.GetService<Person>()!;
    var greeting = context.RequestServices.GetService<Greeting>()!;

    return context.Response.WriteAsync($"{greeting.Message} {person.Name}");
});

app.Run();

public interface IBootstrap
{
    void Register(IServiceCollection services);
}

public class Registration1 : IBootstrap
{
    public void Register(IServiceCollection services)
    {
        services.AddTransient(x => new Person { Name = "Mahmoud" });
    }
}

public class Registration2 : IBootstrap
{
    public void Register(IServiceCollection services)
    {
        services.AddTransient(x => new Greeting { Message = "Good Morning" });
    }
}

public class Person
{
    public string Name { get; set; } = string.Empty;
}

public class Greeting
{
    public string Message { get; set; } = string.Empty;
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *