CommonService.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. namespace Admin.NET.Core.Service;
  2. public class CommonService : ICommonService, IScoped
  3. {
  4. private readonly IHttpContextAccessor _httpContextAccessor;
  5. private readonly CodeGenOptions _codeGenOptions;
  6. public CommonService(IHttpContextAccessor httpContextAccessor, IOptions<CodeGenOptions> codeGenOptions)
  7. {
  8. _httpContextAccessor = httpContextAccessor;
  9. _codeGenOptions = codeGenOptions.Value;
  10. }
  11. /// <summary>
  12. /// 获取库表信息
  13. /// </summary>
  14. /// <returns></returns>
  15. public async Task<IEnumerable<EntityInfo>> GetEntityInfos()
  16. {
  17. var entityInfos = new List<EntityInfo>();
  18. var type = typeof(SugarTable);
  19. var type1 = typeof(NotTableAttribute);
  20. var types = new List<Type>();
  21. if (_codeGenOptions.EntityAssemblyNames != null)
  22. {
  23. foreach (var assemblyName in _codeGenOptions.EntityAssemblyNames)
  24. {
  25. Assembly asm = Assembly.Load(assemblyName);
  26. types.AddRange(asm.GetExportedTypes().ToList());
  27. }
  28. }
  29. Func<Attribute[], bool> IsMyAttribute = o =>
  30. {
  31. if (o.Where(c => c.GetType() == type1).Any()) return false;
  32. foreach (Attribute a in o)
  33. {
  34. if (a.GetType() == type && a.GetType() != type1)
  35. return true;
  36. }
  37. return false;
  38. };
  39. Type[] cosType = types.Where(o =>
  40. {
  41. return IsMyAttribute(Attribute.GetCustomAttributes(o, true));
  42. }
  43. ).ToArray();
  44. foreach (var c in cosType)
  45. {
  46. var sugarAttribute = c.GetCustomAttributes(type, true)?.FirstOrDefault();
  47. var des = c.GetCustomAttributes(typeof(DescriptionAttribute), true);
  48. var description = "";
  49. if (des.Length > 0)
  50. {
  51. description = ((DescriptionAttribute)des[0]).Description;
  52. }
  53. entityInfos.Add(new EntityInfo()
  54. {
  55. EntityName = c.Name,
  56. DbTableName = sugarAttribute == null ? c.Name : ((SugarTable)sugarAttribute).TableName,
  57. TableDescription = description
  58. });
  59. }
  60. return await Task.FromResult(entityInfos);
  61. }
  62. /// <summary>
  63. /// 获取Host
  64. /// </summary>
  65. /// <returns></returns>
  66. public string GetHost()
  67. {
  68. return $"{_httpContextAccessor.HttpContext.Request.Scheme}://{_httpContextAccessor.HttpContext.Request.Host.Value}";
  69. }
  70. /// <summary>
  71. /// 获取文件URL
  72. /// </summary>
  73. /// <param name="sysFile"></param>
  74. /// <returns></returns>
  75. public string GetFileUrl(SysFile sysFile)
  76. {
  77. return $"{GetHost()}/{sysFile.FilePath}/{sysFile.Id + sysFile.Suffix}";
  78. }
  79. }