34

I've got a .NET library in which I need to find all the classes which have a custom attribute I've defined on them, and I want to be able to find them on-the-fly when an application is using my library (ie - I don't want a config file somewhere which I state the assembly to look in and/ or the class names).

I was looking at AppDomain.CurrentDomain but I'm not overly familiar with it and not sure how elivated the privlages need to be (I want to be able to run the library in a Web App with minimal trust if possible, but the lower the trust the happier I'd be). I also want to keep performance in mind (it's a .NET 3.5 library so LINQ is completely valid!).

So is AppDomain.CurrentDomain my best/ only option and then just looping through all the assemblies, and then types in those assemblies? Or is there another way

17 of 26
  • 27,121
  • 13
  • 66
  • 85
Aaron Powell
  • 24,927
  • 18
  • 98
  • 150

2 Answers2

85
IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) 
                              where TAttribute: System.Attribute
 { return from a in AppDomain.CurrentDomain.GetAssemblies()
          from t in a.GetTypes()
          where t.IsDefined(typeof(TAttribute),inherit)
          select t;
 }
Mark Cidade
  • 98,437
  • 31
  • 224
  • 236
  • 1
    It should be noted that this will only find loaded assemblies. If code from an assembly has not been run yet, it isn't loaded so on startup of your application it will not find the assemblies that haven't run. See https://stackoverflow.com/questions/383686/how-do-you-loop-through-currently-loaded-assemblies/26300241#26300241 to get all referenced assemblies. – David Yates Jul 14 '17 at 16:04
3

Mark posted a good answer, but here is a linq free version if you prefer it:

    public static IEnumerable<Type> GetTypesWith<TAttribute>(bool inherit) where TAttribute : Attribute
    {
        var output = new List<Type>();

        var assemblies = AppDomain.CurrentDomain.GetAssemblies();

        foreach (var assembly in assemblies)
        {
            var assembly_types = assembly.GetTypes();

            foreach (var type in assembly_types)
            {
                if (type.IsDefined(typeof(TAttribute), inherit))
                    output.Add(type);
            }
        }

        return output;
    }
Roger Hill
  • 3,677
  • 1
  • 34
  • 38