啊鑫
5 天以前 6b57612f6e9f7575d206e82955ffd989faaaf8b3
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
using Gs.Toolbox.ApiCore.Abstract.Inject;
using Microsoft.Extensions.DependencyInjection;
 
namespace Gs.Toolbox.ApiCore.Common.Inject;
 
public static class InjectTypeManager
{
    public static void Inject(IServiceCollection service, Type interfaceType,
        Type implementType, Type injectType)
    {
        if (injectType.FullName.Equals(typeof(ISingleton).FullName))
            AddISingleton(service, interfaceType, implementType);
        if (injectType.FullName.Equals(typeof(IScope).FullName))
            AddIScope(service, interfaceType, implementType);
        if (injectType.FullName.Equals(typeof(ITransient).FullName))
            AddITransient(service, interfaceType, implementType);
    }
 
    private static void AddISingleton(IServiceCollection service,
        Type interfaceType, Type implementType)
    {
        ImplementTypeThrowException(service, implementType);
        if (interfaceType == null)
        {
            service.AddSingleton(implementType);
            return;
        }
 
        service.AddSingleton(interfaceType, implementType);
    }
 
    private static void ImplementTypeThrowException(IServiceCollection service,
        Type implementType)
    {
        if (implementType == null)
            throw new ArgumentNullException(nameof(implementType));
        if (service == null)
            throw new Exception(
                "ServiceCollection is null,this fail is occur in coustom inject.");
    }
 
    private static void AddIScope(IServiceCollection service,
        Type interfaceType, Type implementType)
    {
        ImplementTypeThrowException(service, implementType);
        if (interfaceType == null)
        {
            service.AddScoped(implementType);
            return;
        }
 
        service.AddScoped(interfaceType, implementType);
    }
 
    private static void AddITransient(IServiceCollection service,
        Type interfaceType, Type implementType)
    {
        ImplementTypeThrowException(service, implementType);
        if (interfaceType == null)
        {
            service.AddTransient(implementType);
            return;
        }
 
        service.AddTransient(interfaceType, implementType);
    }
}