Last active
September 14, 2022 13:16
-
-
Save Ilchert/8c4082c60111b0575d3b6047bd8762fa to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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