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