using Infrastructure.Model;
using Microsoft.Extensions.Options;
using System.Security.Claims;
namespace Infrastructure
{
public static class App
{
///
/// 全局配置文件
///
public static OptionsSetting OptionsSetting => CatchOrDefault(() => ServiceProvider?.GetService>()?.Value);
///
/// 服务提供器
///
public static IServiceProvider ServiceProvider => InternalApp.ServiceProvider;
///
/// 获取请求上下文
///
public static HttpContext HttpContext => CatchOrDefault(() => ServiceProvider?.GetService()?.HttpContext);
///
/// 获取请求上下文用户
///
public static ClaimsPrincipal User => HttpContext?.User;
///
/// 获取用户名
///
public static string UserName => User?.Identity?.Name;
///
/// 获取Web主机环境
///
public static IWebHostEnvironment WebHostEnvironment => InternalApp.WebHostEnvironment;
///
/// 获取全局配置
///
public static IConfiguration Configuration => CatchOrDefault(() => InternalApp.Configuration, new ConfigurationBuilder().Build());
///
/// 获取请求生命周期的服务
///
///
///
public static TService GetService()
where TService : class
{
return GetService(typeof(TService)) as TService;
}
///
/// 获取请求生命周期的服务
///
///
///
public static object GetService(Type type)
{
return ServiceProvider.GetService(type);
}
///
/// 获取请求生命周期的服务
///
///
///
public static TService GetRequiredService()
where TService : class
{
return GetRequiredService(typeof(TService)) as TService;
}
///
/// 获取请求生命周期的服务
///
///
///
public static object GetRequiredService(Type type)
{
return ServiceProvider.GetRequiredService(type);
}
///
/// 处理获取对象异常问题
///
/// 类型
/// 获取对象委托
/// 默认值
/// T
private static T CatchOrDefault(Func action, T defaultValue = null)
where T : class
{
try
{
return action();
}
catch
{
return defaultValue ?? null;
}
}
}
}