-1

my requirement is as follows, is this possible ? if yes can someone please point me to any resources on this ?

  1. get all the assemblies which end with the word "static" from an app domain
  2. get hold of the static class which ends with the word "cache" from the assembly retrieved from step 1
  3. Execute a static method named "invalidate" from the class retrieved from step 2
nen
  • 621
  • 2
  • 10
  • 26
  • http://stackoverflow.com/questions/2639418/use-reflection-to-get-a-list-of-static-classes – CathalMF Feb 12 '15 at 11:27
  • What problem are you trying to solve? This doesn't sounds correct for me. Why can't you call those methods directly in your code. Why do you need a reflection? Is that a plugin model? – Sriram Sakthivel Feb 12 '15 at 11:48
  • A better solution to problems like this is usually to either require objects to register themselves centrally or (if you must have static classes) to apply a custom attribute and use `Attribute.GetCustomAttribute()` to filter types which have this attribute. Selecting by name is much more fragile. Of course, this is only possible if you control the code in question. – Jeroen Mostert Feb 12 '15 at 11:59

1 Answers1

2

Try this:

foreach(Assembly asm in AppDomain.CurrentDomain.GetAssemblies())
{
    if (asm.GetName().Name.EndsWith("static"))
    {
        foreach(Type type in asm.GetTypes())
        {
            if (type.Name.EndsWith("cache"))
            {
                MethodInfo method = type.GetMethod("invalidate", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null);
                if (method != null)
                    method.Invoke(null, null);
            }
        }
    }
}

Or... if you prefer LINQ:

foreach(MethodInfo method in 
    AppDomain.CurrentDomain
    .GetAssemblies().Where(asm => asm.GetName().Name.EndsWith("static"))
    .SelectMany(asm => asm.GetTypes().Where(type => type.Name.EndsWith("cache"))
    .Select(type => type.GetMethod("invalidate", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null)).Where(method => method != null)))
        method.Invoke(null, null);
Martin Mulder
  • 12,642
  • 3
  • 25
  • 54