2

I have a .NET Core 3 Web Api application and I need, during the Startup process, access all of my Controllers methods to see what attributes they have and save this info into a dictionary.

Startup.cs

public void ConfigureServices(IServiceCollection services)
{            
    services.AddControllers(); // is is possible to get more info about the controllers here?
}

I know that I can achieve this using reflection, searching all classes with Controller in the binary and looping through their methods and accessing their atributes. My question is: is there another way? Since I need to add the Controllers in Startup, maybe I can get more info about them?

cash
  • 475
  • 2
  • 7
  • 15
  • 3
    why do you need this information? just curious - perhaps theres another way – Daniel A. White Jan 08 '20 at 16:47
  • @DanielA.White I'm setting all endpoints with an attribute to say which kind of cache strategy I should use, so I want in my Startup to map all strategies and when I execute my CacheMiddleware, I will check in this dictionary to execute the strategy – cash Jan 08 '20 at 16:57
  • that sounds like a great use for a filter – Daniel A. White Jan 08 '20 at 16:59
  • 2
    why are you don't use filters? Filters in ASP.NET Core allow code to be run before or after specific stages in the request processing pipeline [https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.1](https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/filters?view=aspnetcore-3.1) – Mehdi Sheykhveysi Jan 08 '20 at 17:00

1 Answers1

1

You can do it same way Simple Injector does it to register controllers in the container. Something like:

services.AddControllers();
var manager = (ApplicationPartManager)services
    .LastOrDefault(d => d.ServiceType == typeof(ApplicationPartManager))
    .ImplementationInstance;
var feature = new ControllerFeature();
manager.PopulateFeature(feature);
var controllerTypes = feature.Controllers.Select(t => t.AsType());
Andrii Litvinov
  • 12,402
  • 3
  • 52
  • 59