views:

308

answers:

2

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

+11  A: 
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
Simple and workable solution. +1 for this!
eriawan
good stuff - beats have alot of foreach's!
Mike
A: 

Answer doesn't work in Silverlight. "GetAssemblies" is not defined. Any other options?

DMC