Skip to content

Instantly share code, notes, and snippets.

@Ilchert
Last active September 14, 2022 13:16
Show Gist options
  • Save Ilchert/8c4082c60111b0575d3b6047bd8762fa to your computer and use it in GitHub Desktop.
Save Ilchert/8c4082c60111b0575d3b6047bd8762fa to your computer and use it in GitHub Desktop.
public static class ServiceCollectionExtensions
{
internal static readonly string ModulesKey = "Modules";
public static IServiceCollection AddModules(this IServiceCollection serviceCollection, HostBuilderContext builderContext)
{
var modulesSection = builderContext.Configuration.GetSection(ModulesKey);
foreach (var moduleName in modulesSection.GetChildren())
{
var type = Type.GetType(moduleName.Value, true, false);
if (type == null)
throw new InvalidOperationException($"Module name {moduleName.Value} was not resolved.");
var module = (IConfigurationModule)Activator.CreateInstance(type)!;
serviceCollection.AddModule(builderContext, module);
}
return serviceCollection;
}
public static IServiceCollection AddModule(this IServiceCollection serviceCollection, HostBuilderContext builderContext, IConfigurationModule module)
{
module.ConfigureServices(builderContext, serviceCollection);
return serviceCollection;
}
}
public interface IConfigurationModule
{
void ConfigureServices(HostBuilderContext context, IServiceCollection services);
}
// appsettings.json
{
"Modules": ["ClassName, LibName"]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment