StartUpExtenions.cs
3.17 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace Hh.Mes.Service.Repository
{
/// <summary>
/// DI实现批量注册
/// </summary>
public static class StartUpExtenions
{
/// <summary>
/// 批量注册服务
/// </summary>
/// <param name="services">DI服务</param>
/// <param name="assemblys">需要批量注册的程序集集合 如果有过多头号隔开</param>
/// <param name="suffix"> 业务都有固定的后缀,可以自己定义命名规则,例如XXXReository, XXXService等</param>
/// <param name="serviceLifetime">服务生命周期</param>
/// <returns></returns>
public static IServiceCollection BatchRegisterService(this IServiceCollection services, string assemblys, string suffix, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
if (string.IsNullOrEmpty(assemblys)) return null;
//待注册集合
var typeDic = GetImpleAndInterfaces(assemblys,suffix);
//var index = 0;
//foreach (var temp in typeDic)
//{
// foreach (var v in temp)
// {
// index++;
// Console.WriteLine($"class={v.FullName}");
// }
//}
//Console.WriteLine($"{suffix}接口及实现个数为:{index}");
if (!typeDic.Any()) return services;
foreach (var instanceType in typeDic)
{
foreach (var tempClass in instanceType)
{
//根据指定的生命周期进行注册
switch (serviceLifetime)
{
case ServiceLifetime.Scoped:
services.AddScoped(tempClass);
break;
case ServiceLifetime.Singleton:
services.AddSingleton(tempClass);
break;
case ServiceLifetime.Transient:
services.AddTransient(tempClass);
break;
}
}
}
return services;
}
/// <summary>
/// 载入指定的DLL(根据DLL名字载入)
/// </summary>
/// <param name="assemblyName"></param>
/// <param name="suffix"></param>
/// <returns></returns>
private static List<List<Type>> GetImpleAndInterfaces(string assemblyName, string suffix)
{
var result = new List<List<Type>>();
var assemblyArr = assemblyName.Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var temp in assemblyArr)
{
Assembly assembly = Assembly.Load(temp);
var types = assembly
.GetTypes()
.Where(x => x.IsClass && x.Name.Contains(suffix))
.ToList();
result.Add(types);
}
return result;
}
}
}