Skip to content

Instantly share code, notes, and snippets.

@JaimeStill
Last active March 16, 2023 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JaimeStill/aadf675df5022b0697b2e28d5047d69d to your computer and use it in GitHub Desktop.
Save JaimeStill/aadf675df5022b0697b2e28d5047d69d to your computer and use it in GitHub Desktop.
Service Registration via Reflection in .NET
using Microsoft.Extensions.DependencyInjection;
namespace App.Services;
public class AppServiceRegistrant : ServiceRegistrant
{
public AppServiceRegistrant(IServiceCollection services)
: base(services) { }
public override void Register()
{
services.AddScoped<ServiceA>();
services.AddScoped<ServiceB>();
//
services.AddScoped<ServiceZ>();
}
}
using App.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAppServices();
var app = builder.Build();
app.Run();
using Microsoft.Extensions.DependencyInjection;
namespace App.Services;
public abstract class ServiceRegistrant
{
protected readonly IServiceCollection services;
public ServiceRegistrant(IServiceCollection services)
{
this.services = services;
}
public abstract void Register();
}
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
namespace App.Services;
public static class ServiceRegistration
{
public static void AddAppServices(this IServiceCollection services)
{
IEnumerable<Type> registrants = Assembly
.GetAssembly(typeof(ServiceRegistrant))
.GetTypes()
.Where(x =>
x.IsClass
&& !x.IsAbstract
&& x.IsSubclassOf(typeof(ServiceRegistrant))
);
foreach (Type registrant in registrants)
((ServiceRegistrant)Activator.CreateInstance(registrant, services)).Register();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment