0

I have a class with a custom attribute that has a string parameter.

[ANAttribute("Ampe21")]
public class ClassB : ClassA
{

}

I have different action names defined for different classes.

What I want is to obtain the namespace of ClassB or obtain the type of ClassB by searching the entire application after Ampe21.

How can I do that?

tzortzik
  • 4,993
  • 9
  • 57
  • 88

1 Answers1

1

You can search all the loaded assemblies like this:

var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany
    (x => x.GetTypes()
        .Where(t => t.GetCustomAttribute<ANAttribute>() != null &&
                    t.GetCustomAttribute<ANAttribute>().YourProperty == "Ampe21")
    );

foreach (var type in types)
{
    Console.WriteLine(type.Namespace);
}

You can avoid calling GetCustomAttribute twice by introducing a local variable.

If your assembly is not yet loaded, this will skip the assembly. You may load it using Assembly.Load but not recommended.

Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • It seems to work partially. It finds all my classes from namespace `A.B.C` but it doesn't find the ones from `A.Controllers`. Any idea why? I was thinking that assembly must be loaded manually but I didn't know how to do that. – tzortzik Aug 05 '14 at 15:13
  • I've just tried to apply an attribute on a class from another namespace that is not contained in controller and it works... But still, I cannot apply it on controller – tzortzik Aug 05 '14 at 15:19
  • I've just found the problem. I was doing something completely wrong. By using the piece of code that Sriram provided it was working for classes but in my controller I applied the attribute on methods so this is the reason why it was partially working. – tzortzik Aug 05 '14 at 15:20
  • 1
    @tzortzik It is not a good idea to load manually. You may get your [answer here](http://stackoverflow.com/questions/2384592/c-net-is-there-a-way-to-force-all-referenced-assemblies-to-be-loaded-into-the) – Sriram Sakthivel Aug 05 '14 at 15:20
  • @tzortzik Am glad that you found the issue. – Sriram Sakthivel Aug 05 '14 at 15:21