-
Notifications
You must be signed in to change notification settings - Fork 0
/
AspNetCoreServiceTools.cs
68 lines (66 loc) · 2.27 KB
/
AspNetCoreServiceTools.cs
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
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
using System.Reflection;
public static class AspNetCoreServiceTools
{
/// <summary>
/// 注入服务
/// </summary>
/// <param name="services"></param>
/// <param name="dllName">注入项目名称</param>
/// <returns></returns>
public static IServiceCollection RegisterServices(this IServiceCollection services, string dllName)
{
if (!string.IsNullOrEmpty(dllName))
{
//获取dll
var types = Assembly.Load(dllName).GetExportedTypes().ToList();
//获取dll下所有类型
foreach (var item in types)
{
//类型必须是类 实现接口必须大于0
if (item.IsClass && item.GetInterfaces().Length > 0)
{
foreach (var iSer in item.GetInterfaces())
{
DI(services, item, iSer);
}
}
else if (item.IsClass && item.GetInterfaces().Length <= 0)
{
DI(services, item);
}
}
}
return services;
}
private static void DI(IServiceCollection services, Type item, Type interFace = null)
{
var attribute = item.GetCustomAttributes(typeof(IdentifyingAttribute), true);
if (attribute.Any())
{
switch (((IdentifyingAttribute)attribute[0]).ServiceLifeTime.ToString())
{
case "Transient" when interFace != null:
services.AddTransient(interFace, item);
break;
case "Scoped" when interFace != null:
services.AddScoped(interFace, item);
break;
case "Singleton" when interFace != null:
services.AddSingleton(interFace, item);
break;
case "Transient":
services.AddTransient(item);
break;
case "Scoped":
services.AddScoped(item);
break;
case "Singleton":
services.AddSingleton(item);
break;
}
}
}
}