Advertisement
commodore73

Base class for attributes

Jul 23rd, 2020
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.13 KB | None | 0 0
  1. namespace Deliverystack.Core.Attributes
  2. {
  3.     using System;
  4.     using System.Collections.Concurrent;
  5.     using System.Collections.Generic;
  6.     using System.Reflection;
  7.  
  8.     public abstract class AttributeBase : Attribute
  9.     {
  10.         // map the type of the attribute to a list of types that have that attribute.
  11.         // static and cached to optimize performance.
  12.         private static ConcurrentDictionary<Type, List<Type>> _types =
  13.             new ConcurrentDictionary<Type, List<Type>>();
  14.        
  15.         public static Type[] GetTypesWithAttribute(Type attribute)
  16.         {
  17.             // Have assemblies already been scanned for this attribute.
  18.             if (!_types.ContainsKey(attribute))
  19.             {
  20.                 // no, create a new entry in the dictionary mapping
  21.                 // the attribute to the list of types that have that attribute.
  22.                 List<Type> result = new List<Type>();
  23.  
  24.                 // for each assembly available
  25.                 foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
  26.                 {
  27.                     try
  28.                     {
  29.                         // for each type in the assembly
  30.                         foreach (Type type in assembly.GetTypes())
  31.                         {
  32.                             // if the type has the attribute
  33.                             if (type.GetCustomAttributes(attribute, true).Length > 0)
  34.                             {
  35.                                 // then add it to the list of types for the attribute
  36.                                 result.Add(type);
  37.                             }
  38.                         }
  39.                     }
  40.                     catch (Exception ex)
  41.                     {
  42.                         // ignore; unable to load; assembly may be obfuscated, etc.
  43.                     }
  44.                 }
  45.  
  46.                 // store a record mapping the attribute to the list of types with that attribute
  47.                 _types[attribute] = result;
  48.             }
  49.  
  50.             // return the list of types with the attribute
  51.             return _types[attribute].ToArray();
  52.         }
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement