de2bd2f9
“wangming”
项目初始化
|
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
|
using NCC;
using NCC.Dependency;
using NCC.DynamicApiController;
using NCC.Reflection;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// 依赖注入拓展类
/// </summary>
[SuppressSniffer]
public static class DependencyInjectionServiceCollectionExtensions
{
/// <summary>
/// 添加依赖注入接口
/// </summary>
/// <param name="services">服务集合</param>
/// <returns>服务集合</returns>
public static IServiceCollection AddDependencyInjection(this IServiceCollection services)
{
// 添加外部程序集配置
services.AddConfigurableOptions<DependencyInjectionSettingsOptions>();
services.AddInnerDependencyInjection();
return services;
}
/// <summary>
/// 添加接口代理
/// </summary>
/// <typeparam name="TDispatchProxy">代理类</typeparam>
/// <typeparam name="TIDispatchProxy">被代理接口依赖</typeparam>
/// <param name="services">服务集合</param>
/// <returns>服务集合</returns>
public static IServiceCollection AddScopedDispatchProxyForInterface<TDispatchProxy, TIDispatchProxy>(this IServiceCollection services)
where TDispatchProxy : AspectDispatchProxy, IDispatchProxy
where TIDispatchProxy : class
{
// 注册代理类
services.AddScoped<AspectDispatchProxy, TDispatchProxy>();
// 代理依赖接口类型
var proxyType = typeof(TDispatchProxy);
var typeDependency = typeof(TIDispatchProxy);
// 获取所有的代理接口类型
var dispatchProxyInterfaceTypes = App.EffectiveTypes
.Where(u => typeDependency.IsAssignableFrom(u) && u.IsInterface && u != typeDependency);
// 注册代理类型
foreach (var interfaceType in dispatchProxyInterfaceTypes)
{
AddDispatchProxy(services, typeof(IScoped), default, proxyType, interfaceType, false);
}
return services;
}
/// <summary>
/// 添加扫描注入
/// </summary>
/// <param name="services">服务集合</param>
/// <returns>服务集合</returns>
private static IServiceCollection AddInnerDependencyInjection(this IServiceCollection services)
{
// 查找所有需要依赖注入的类型
var injectTypes = App.EffectiveTypes
.Where(u => typeof(IPrivateDependency).IsAssignableFrom(u) && u.IsClass && !u.IsInterface && !u.IsAbstract)
.OrderBy(u => GetOrder(u));
var projectAssemblies = App.Assemblies;
var lifetimeInterfaces = new[] { typeof(ITransient), typeof(IScoped), typeof(ISingleton) };
// 执行依赖注入
foreach (var type in injectTypes)
{
// 获取注册方式
var injectionAttribute = !type.IsDefined(typeof(InjectionAttribute)) ? new InjectionAttribute() : type.GetCustomAttribute<InjectionAttribute>();
var interfaces = type.GetInterfaces();
// 获取所有能注册的接口
var canInjectInterfaces = interfaces.Where(u => !injectionAttribute.ExpectInterfaces.Contains(u)
&& u != typeof(IPrivateDependency)
&& u != typeof(IDynamicApiController)
&& !lifetimeInterfaces.Contains(u)
&& projectAssemblies.Contains(u.Assembly)
&& (
(!type.IsGenericType && !u.IsGenericType)
|| (type.IsGenericType && u.IsGenericType && type.GetGenericArguments().Length == u.GetGenericArguments().Length))
);
// 获取生存周期类型
var dependencyType = interfaces.Last(u => lifetimeInterfaces.Contains(u));
// 注册服务
RegisterService(services, dependencyType, type, injectionAttribute, canInjectInterfaces);
// 缓存类型注册
var typeNamed = injectionAttribute.Named ?? type.Name;
TypeNamedCollection.TryAdd(typeNamed, type);
}
// 注册外部配置服务
RegisterExternalServices(services);
// 注册命名服务(接口多实现)
RegisterNamedService<ITransient>(services);
RegisterNamedService<IScoped>(services);
RegisterNamedService<ISingleton>(services);
return services;
}
/// <summary>
/// 注册服务
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="dependencyType"></param>
/// <param name="type">类型</param>
/// <param name="injectionAttribute">注入特性</param>
/// <param name="canInjectInterfaces">能被注册的接口</param>
private static void RegisterService(IServiceCollection services, Type dependencyType, Type type, InjectionAttribute injectionAttribute, IEnumerable<Type> canInjectInterfaces)
{
// 注册自己
if (injectionAttribute.Pattern is InjectionPatterns.Self or InjectionPatterns.All or InjectionPatterns.SelfWithFirstInterface)
{
Register(services, dependencyType, type, injectionAttribute);
}
if (!canInjectInterfaces.Any()) return;
// 只注册第一个接口
if (injectionAttribute.Pattern is InjectionPatterns.FirstInterface or InjectionPatterns.SelfWithFirstInterface)
{
Register(services, dependencyType, type, injectionAttribute, canInjectInterfaces.Last());
}
// 注册多个接口
else if (injectionAttribute.Pattern is InjectionPatterns.ImplementedInterfaces or InjectionPatterns.All)
{
foreach (var inter in canInjectInterfaces)
{
Register(services, dependencyType, type, injectionAttribute, inter);
}
}
}
/// <summary>
/// 注册类型
/// </summary>
/// <param name="services">服务</param>
/// <param name="dependencyType"></param>
/// <param name="type">类型</param>
/// <param name="injectionAttribute">注入特性</param>
/// <param name="inter">接口</param>
private static void Register(IServiceCollection services, Type dependencyType, Type type, InjectionAttribute injectionAttribute, Type inter = null)
{
// 修复泛型注册类型
var fixedType = FixedGenericType(type);
var fixedInter = inter == null ? null : FixedGenericType(inter);
switch (injectionAttribute.Action)
{
case InjectionActions.Add:
if (fixedInter == null) services.InnerAdd(dependencyType, fixedType);
else
{
services.InnerAdd(dependencyType, fixedInter, fixedType);
AddDispatchProxy(services, dependencyType, fixedType, injectionAttribute.Proxy, fixedInter, true);
}
break;
case InjectionActions.TryAdd:
if (fixedInter == null) services.InnerTryAdd(dependencyType, fixedType);
else services.InnerTryAdd(dependencyType, fixedInter, fixedType);
break;
default: break;
}
}
/// <summary>
/// 创建服务代理
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="dependencyType"></param>
/// <param name="type">拦截的类型</param>
/// <param name="proxyType">代理类型</param>
/// <param name="inter">代理接口</param>
/// <param name="hasTarget">是否有实现类</param>
private static void AddDispatchProxy(IServiceCollection services, Type dependencyType, Type type, Type proxyType, Type inter, bool hasTarget = true)
{
proxyType ??= GlobalServiceProxyType;
if (proxyType == null || (type != null && type.IsDefined(typeof(SuppressProxyAttribute), true))) return;
// 注册代理类型
services.InnerAdd(dependencyType, typeof(AspectDispatchProxy), proxyType);
// 注册服务
services.InnerAdd(dependencyType, inter, provider =>
{
dynamic proxy = DispatchCreateMethod.MakeGenericMethod(inter, proxyType).Invoke(null, null);
proxy.Services = provider;
if (hasTarget)
{
proxy.Target = provider.GetService(type);
}
return proxy;
});
}
/// <summary>
/// 注册命名服务(接口多实现)
/// </summary>
/// <typeparam name="TDependency"></typeparam>
/// <param name="services"></param>
private static void RegisterNamedService<TDependency>(IServiceCollection services)
where TDependency : IPrivateDependency
{
// 注册命名服务
services.InnerAdd(typeof(TDependency), provider =>
{
object ResolveService(string named, TDependency _)
{
var isRegister = TypeNamedCollection.TryGetValue(named, out var serviceType);
return isRegister ? provider.GetService(serviceType) : null;
}
return (Func<string, TDependency, object>)ResolveService;
});
}
/// <summary>
/// 注册外部服务
/// </summary>
/// <param name="services"></param>
private static void RegisterExternalServices(IServiceCollection services)
{
// 获取选项
var externalServices = App.GetConfig<DependencyInjectionSettingsOptions>("DependencyInjectionSettings", true);
if (externalServices is { Definitions: not null })
{
// 排序
var extServices = externalServices.Definitions.OrderBy(u => u.Order);
foreach (var externalService in extServices)
{
var injectionAttribute = new InjectionAttribute
{
Action = externalService.Action,
Named = externalService.Named,
Order = externalService.Order,
Pattern = externalService.Pattern
};
// 加载代理拦截
if (!string.IsNullOrWhiteSpace(externalService.Proxy)) injectionAttribute.Proxy = GetProxyType(externalService.Proxy);
// 解析注册类型
var dependencyType = externalService.RegisterType switch
{
RegisterType.Transient => typeof(ITransient),
RegisterType.Scoped => typeof(IScoped),
RegisterType.Singleton => typeof(ISingleton),
_ => throw new InvalidOperationException("Unknown lifetime type.")
};
RegisterService(services, dependencyType,
GetProxyType(externalService.Service),
injectionAttribute,
new[] { GetProxyType(externalService.Interface) });
}
}
}
/// <summary>
/// 修复泛型类型注册类型问题
/// </summary>
/// <param name="type">类型</param>
/// <returns></returns>
private static Type FixedGenericType(Type type)
{
if (!type.IsGenericType) return type;
return Reflect.GetType(type.Assembly, $"{type.Namespace}.{type.Name}");
}
/// <summary>
/// 获取 注册 排序
/// </summary>
/// <param name="type">排序类型</param>
/// <returns>int</returns>
private static int GetOrder(Type type)
{
return !type.IsDefined(typeof(InjectionAttribute), true) ? 0 : type.GetCustomAttribute<InjectionAttribute>(true).Order;
}
/// <summary>
/// 加载代理程序集
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static Type GetProxyType(string str)
{
var typeDefinitions = str.Split(";");
return Reflect.GetType(typeDefinitions[0], typeDefinitions[1]);
}
/// <summary>
/// 类型名称集合
/// </summary>
private static readonly ConcurrentDictionary<string, Type> TypeNamedCollection;
/// <summary>
/// 创建代理方法
/// </summary>
private static readonly MethodInfo DispatchCreateMethod;
/// <summary>
/// 全局服务代理类型
/// </summary>
private static readonly Type GlobalServiceProxyType;
/// <summary>
/// 静态构造函数
/// </summary>
static DependencyInjectionServiceCollectionExtensions()
{
// 获取全局代理类型
GlobalServiceProxyType = App.EffectiveTypes
.FirstOrDefault(u => typeof(AspectDispatchProxy).IsAssignableFrom(u) && typeof(IGlobalDispatchProxy).IsAssignableFrom(u) && u.IsClass && !u.IsInterface && !u.IsAbstract);
TypeNamedCollection = new ConcurrentDictionary<string, Type>();
DispatchCreateMethod = typeof(AspectDispatchProxy).GetMethod(nameof(AspectDispatchProxy.Create));
}
}
}
|