views:

28

answers:

3

Hi - I'm a bit new to reflection in c#. I'm trying to generate a list of all controllers in order to test whether or not they are decorated with a specific actionfilter. When writing unit tests, how do you access the tested assembly?

This does not seem to work:

var myAssembly = System.Reflection.Assembly.GetExecutingAssembly();
+1  A: 

If you know a type in your main assembly, you can use:

    private IEnumerable<Type> GetControllers()
    {
        return from t in typeof(MyType).Assembly.GetTypes()
               where t.IsAbstract == false
               where typeof(Controller).IsAssignableFrom(t)
               where t.Name.EndsWith("Controller", StringComparison.OrdinalIgnoreCase)
               select t;
    }

Replace MyType with the known type.

I use this in a base class with this.GetType() instead of typeof(MyType), so that I can reference the assembly in which the derrived type is defined.

John Gietzen
Thanks John. One question: Isn't the "where typeof(Controller).IsAssignableFrom(t)" sufficient enough to confirm that it's a controller type? I'm a bit new to Linq too, btw :)
morganpdx
Yes, that should be sufficient. I just looked at the source code of MVC, and it looks like they don't care if it `EndWith("Controller")` so you might take that part out.
John Gietzen
A: 

You will know the name of the assembly at the time that you write your tests. Using Assembly.ReflectionOnlyLoad() is an appropriate choice for this scenario.

As an alternative, you can draw from the Assembly property of any single known type from the assembly.

kbrimington
A: 

Assembly.GetAssemblyByName() is probably the ticket to look for an assembly other than yours. It'll look in your application's assembly bindings, then in the current application directory, then in the GAC. You can also get the Assembly class given an object instance or a statically-referenced type by calling GetType().Assembly.

From this Assembly class, you can iterate through the types contained in it as Type objects using GetExportedTypes(). This will return public types only; the ones you could access if you referenced the assembly statically. You can filter these by anything you can reflectively analyze; name, parent types, member names, attributes decorating the class or any member, etc.

KeithS