新框架PC后端代码(祈禧6月初版本)
南骏 池
4 天以前 72449a1b8699b65712e57fba8abce5a8240e9465
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
using Gs.Toolbox.ApiCore.Abstract;
using Gs.Toolbox.ApiCore.Common.Mvc;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc.ApplicationParts;
using Microsoft.Extensions.DependencyInjection;
 
namespace Gs.Toolbox.ApiCore.Extensions;
 
public static class ApplicationExtension
{
    public static void AddCustomController(this WebApplication app)
    {
        using (var serviceScope = app.Services.CreateScope())
        {
            var services = serviceScope.ServiceProvider;
            var applicationPartManager =
                services.GetRequiredService<ApplicationPartManager>();
            if (applicationPartManager == null)
                throw new Exception("未在容器中找到ApplicationPartManager");
            applicationPartManager.FeatureProviders.Add(
                new CustomControllerFeatureProvider());
        }
    }
 
    public static void AddModule<T>(this WebApplication app) where T : IModule
    {
        var list = new List<Type>();
        Rescuise(typeof(T), list);
        //去重,然后加载配置
        var tempList = new List<Type>();
        foreach (var t in list)
            if (!tempList.Contains(t))
                tempList.Add(t);
 
        using (var serviceScope = app.Services.CreateScope())
        {
            var services = serviceScope.ServiceProvider;
            var serviceCollection =
                services.GetRequiredService<IServiceCollection>();
            execModule(tempList, app, serviceCollection);
        }
    }
 
    private static void execModule(List<Type> tempList, WebApplication app,
        IServiceCollection serviceCollection)
    {
        foreach (var module in tempList)
        {
            var mod = (IModule)Activator.CreateInstance(module);
            mod.ConfigService(serviceCollection);
        }
 
        foreach (var module in tempList)
        {
            var mod = (IModule)Activator.CreateInstance(module);
            mod.ApplicationConfig(app);
        }
    }
 
    public static void Rescuise(Type type, List<Type> list)
    {
        var attr = type.GetCustomAttributes(false);
        if (attr.Length == 0)
        {
            list.Add(type);
            return;
        }
 
        foreach (var a in attr)
        {
            var temp = (CustomDependenceAttribute)a;
            Rescuise(temp.DependType, list);
        }
 
        list.Add(type);
    }
}