App.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.Extensions.DependencyInjection;
  3. using System;
  4. using System.Security.Claims;
  5. namespace Infrastructure
  6. {
  7. public static class App
  8. {
  9. /// <summary>
  10. /// 服务提供器
  11. /// </summary>
  12. public static IServiceProvider ServiceProvider => HttpContext?.RequestServices ?? InternalApp.ServiceProvider;
  13. /// <summary>
  14. /// 获取请求上下文
  15. /// </summary>
  16. public static HttpContext HttpContext => HttpContextLocal.Current();
  17. /// <summary>
  18. /// 获取请求上下文用户
  19. /// </summary>
  20. public static ClaimsPrincipal User => HttpContext?.User;
  21. /// <summary>
  22. /// 获取请求生命周期的服务
  23. /// </summary>
  24. /// <typeparam name="TService"></typeparam>
  25. /// <returns></returns>
  26. public static TService GetService<TService>()
  27. where TService : class
  28. {
  29. return GetService(typeof(TService)) as TService;
  30. }
  31. /// <summary>
  32. /// 获取请求生命周期的服务
  33. /// </summary>
  34. /// <param name="type"></param>
  35. /// <returns></returns>
  36. public static object GetService(Type type)
  37. {
  38. return ServiceProvider.GetService(type);
  39. }
  40. /// <summary>
  41. /// 获取请求生命周期的服务
  42. /// </summary>
  43. /// <typeparam name="TService"></typeparam>
  44. /// <returns></returns>
  45. public static TService GetRequiredService<TService>()
  46. where TService : class
  47. {
  48. return GetRequiredService(typeof(TService)) as TService;
  49. }
  50. /// <summary>
  51. /// 获取请求生命周期的服务
  52. /// </summary>
  53. /// <param name="type"></param>
  54. /// <returns></returns>
  55. public static object GetRequiredService(Type type)
  56. {
  57. return ServiceProvider.GetRequiredService(type);
  58. }
  59. }
  60. }