Finding all classes with a particular attribute
Asked Answered
C

2

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

Casady answered 6/4, 2009 at 3:10 Comment(0)
P
86
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;
 }
Phantom answered 6/4, 2009 at 3:19 Comment(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 #384186 to get all referenced assemblies.Dora
F
4

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;
    }

I like this over the answer that uses linq, because its much easier to debug and step through. It also lends itself nicely for more complicated logic within each step.

I think Linq is fantastic for simple things, but it can get pretty gnarly to maintain as the complexity of the filter/transform rises.

Frustule answered 26/10, 2017 at 23:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.