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
|
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;
namespace NCC.Dependency
{
/// <summary>
/// 创建作用域静态类
/// </summary>
[SuppressSniffer]
public static partial class Scoped
{
/// <summary>
/// 创建一个作用域范围
/// </summary>
/// <param name="handler"></param>
/// <param name="scopeFactory"></param>
public static void Create(Action<IServiceScopeFactory, IServiceScope> handler, IServiceScopeFactory scopeFactory = default)
{
Create(async (fac, scope) =>
{
handler(fac, scope);
await Task.CompletedTask;
}, scopeFactory).GetAwaiter().GetResult();
}
/// <summary>
/// 创建一个作用域范围
/// </summary>
/// <param name="handler"></param>
/// <param name="scopeFactory"></param>
public static async Task Create(Func<IServiceScopeFactory, IServiceScope, Task> handler, IServiceScopeFactory scopeFactory = default)
{
// 禁止空调用
if (handler == null) throw new ArgumentNullException(nameof(handler));
// 创建作用域
var scoped = CreateScope(scopeFactory);
try
{
// 执行方法
await handler(scopeFactory, scoped);
}
finally
{
// 释放
scoped.Dispose();
}
}
/// <summary>
/// 创建一个作用域
/// </summary>
/// <param name="scopeFactory"></param>
/// <returns></returns>
private static IServiceScope CreateScope(IServiceScopeFactory scopeFactory = default)
{
// 解析服务作用域工厂
var scoped = (scopeFactory ?? App.RootServices.GetService<IServiceScopeFactory>()).CreateScope();
return scoped;
}
}
}
|