Flip controller list

I'm a little new to thinking in C #. I am trying to create a list of all controllers to check if they are decorated with a specific actionfilter file. When writing unit tests, how do you access the assembly under test?

This does not work:

var myAssembly = System.Reflection.Assembly.GetExecutingAssembly(); 
+6
reflection c # unit-testing asp.net-mvc-2
source share
3 answers

If you know the type of 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 a known type.

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

+4
source share

You will learn the assembly name when you write your tests. Using Assembly.ReflectionOnlyLoad() is the appropriate choice for this scenario.

Alternatively, you can extract from the Assembly property any one known type from the assembly.

0
source share

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

From this Assembly class, you can iterate over the types contained in it as type objects using GetExportedTypes() . This will only result in public types; the ones you could get if you statically referenced the assembly. You can filter them for anything you can analyze analytically; name, parent types, member names, attributes decorating a class or any member, etc.

0
source share

All Articles