Last active
March 16, 2023 19:11
-
-
Save JaimeStill/aadf675df5022b0697b2e28d5047d69d to your computer and use it in GitHub Desktop.
Service Registration via Reflection in .NET
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using App.Services; | |
var builder = WebApplication.CreateBuilder(args); | |
builder.Services.AddAppServices(); | |
var app = builder.Build(); | |
app.Run(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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