AssemblyGitHashLookup.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. namespace VCommon.Reflection
  6. {
  7. public static class AssemblyGitHashLookup
  8. {
  9. private const string MetaKey = "GitHash";
  10. private static readonly LazyHolder<IReadOnlyDictionary<string, IReadOnlyCollection<Assembly>>> Holder = new LazyHolder<IReadOnlyDictionary<string, IReadOnlyCollection<Assembly>>>(CreateDic);
  11. public static IReadOnlyDictionary<string, IReadOnlyCollection<Assembly>> All => Holder.Instance;
  12. public static IReadOnlyDictionary<string, IReadOnlyCollection<string>> AllNames => All.ToDictionary(p => p.Key, p => (IReadOnlyCollection<string>)p.Value.Select(a => a.GetName().Name).ToArray());
  13. private static IReadOnlyDictionary<string, IReadOnlyCollection<Assembly>> CreateDic()
  14. {
  15. var dic = AppDomain.CurrentDomain.GetAssemblies().Where(p =>
  16. {
  17. if (false == p.IsDefined(typeof(AssemblyMetadataAttribute))) return false;
  18. return p.GetCustomAttributes<AssemblyMetadataAttribute>().Any(attr => attr.Key == MetaKey);
  19. }).GroupBy(p =>
  20. p.GetCustomAttributes<AssemblyMetadataAttribute>()
  21. .Where(attr => attr.Key == MetaKey)
  22. .Select(attr => attr.Value)
  23. .First()
  24. ).ToDictionary(p => p.Key, p => (IReadOnlyCollection<Assembly>)p.ToArray());
  25. return dic;
  26. }
  27. }
  28. }