Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Load an Assembly and get a custom attribute from specific methods

I have a code snip that I load a dll and I am trying to get a custom attribute type.
The custom type is declared in the SomeDll

// SomeDll.dll
[SomeCustomAttribute]
public void Foo()
{
}

This is the second project below

public static void Main(string[] args)
{
   string dllPath = @".\SomeDll.dll";

   var assembly = Assembly.LoadFrom(dllPath);

   var testMethods = assembly.GetTypes()
      .SelectMany(t => t.GetMethods())
      .Where(m => m.GetCustomAttributes("HOW CAN I GET SomeCustomAttribute HERE?")
      .ToArray();
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The easiest is to loop the attributes returned by GetCustomAttributes and check their names:

var testMethods = assembly.GetTypes()
    .SelectMany(t => t.GetMethods())
    .Where(m => m.GetCustomAttributes(false).FirstOrDefault()?.GetType().Name == "SomeCustomAttribute")
    .ToArray();

Alternativly you may first get the type of the attribute and use that for GetCustomAttributes:

var type = assembly.GetType("The.Namespace.SomeCustomAttribute");
var testMethods = assembly.GetTypes()
    .SelectMany(t => t.GetMethods())
    .Where(m => m.GetCustomAttributes(type, false).Any())
    .ToArray();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading