-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDiExtensions.cs
More file actions
62 lines (53 loc) · 2.11 KB
/
DiExtensions.cs
File metadata and controls
62 lines (53 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using System.Reflection;
using System.Runtime.Loader;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Logrus.Ext;
public static class DiExtensions
{
public static TSetting AddSettings<TSetting>(this IServiceCollection services, IConfiguration configuration)
where TSetting : class
{
var settings = configuration.GetRequiredSection(typeof(TSetting).Name).Get<TSetting>()
?? throw new ArgumentException($"Settings not found: {typeof(TSetting)}");
services.AddSingleton(settings);
return settings;
}
public static void AddModules(this IServiceCollection services, IConfiguration configuration, params Type[] moduleTypes)
{
AddModulesInternal(services, configuration, moduleTypes);
var dynamicModules = configuration.GetSection("Logrus:Ext:DynamicModules");
if (!dynamicModules.Exists()) return;
foreach (var assemblyPath in dynamicModules.Get<string[]>() ?? [])
{
moduleTypes = AssemblyLoadContext.Default
.LoadFromAssemblyPath(assemblyPath)
.GetTypes()
.Where(x => x.IsAssignableTo(typeof(IModule)))
.ToArray();
AddModulesInternal(services, configuration, moduleTypes);
}
}
private static void AddModulesInternal(IServiceCollection services, IConfiguration configuration,
Type[] moduleTypes)
{
var modules = moduleTypes.Select(Activator.CreateInstance).Cast<IModule>();
foreach (var module in modules)
{
services.AddSingleton(module);
module.RegisterServices(services, configuration);
}
}
public static void AddPlugin<TApi, TImpl>(this IServiceCollection services, string code)
where TApi : class where TImpl : class, TApi
{
services.AddKeyedTransient<TApi, TImpl>(code);
}
public static async Task RunModules(this IServiceProvider services)
{
foreach (var module in services.GetServices<IModule>())
{
await module.RunServices(services);
}
}
}