I have a marker interface something like this:
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false, Inherited=true)]
public class MyAttribute : Attribute
{
}
And i want to apply it to methods on different classes in different assemblies...
Then I want to Get a MethodInfo for all methods that have this attribute applied. I need to search the whole AppDomain and get a reference to all these methods.
I know we can get all types and then get all methods, but is there a quicker/better way to do this? ... or is this the quickest manner to get the information I need?
(I'm using ASP.NET MVC 1.0, C#, ./NET 3.5)
Thanks heaps!
Ultimately, no - you have to scan them. LINQ makes it fairly pain-free though.
var qry = from asm in AppDomain.CurrentDomain.GetAssemblies()
from type in asm.GetTypes()
from method in type.GetMethods()
where Attribute.IsDefined(method, typeof(MyAttribute))
select method;
Note this only scans loaded assemblies "as is".
One thing you should consider is an additional attribute that you can apply to a class/struct, indicating that zero or more methods of that type are marked. That should give you at least an order of magnitude improvement in performance.
If the attribute is user-defined (not built in to the .NET framework), then when you're enumerating the assemblies to get the types, you should skip framework assemblies such as mscorlib and System.
If you really need the performance gain, do as Marc suggested and then cache the results in a file. The next time the application load, if the cached file exists, it can load the appropriate method without parsing every assemblies.
Here is an example of a possible cache file:
<attributeCache>
<assembly name='Assembly1' filename='Assembly1.dll' timestamp='02/02/2010'>
<type name='Assembly1.Type1'>
<method name='Method1'/>
</type>
</assembly>
<assembly name='Assembly2' filename='Assembly2.dll' timestamp='02/02/2010' />
</attributeCache>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With