Reputation: 806
I am using NSwag to generate the controller code for a c# Open API service
Then, in Program.cs, it is just a simple code from the sample project
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
I can run and test the service, which is fine here.
But what I do not understand is that I do not specify the generated controller class name in the method call of builder.Services.AddControllers() or app.MapControllers().
How does the runtime know which controller it should use, what/where is the magic?
Is it something done by reflection by the underlying framework? I mean to loop all the classes and find those implementing the controller interface?
If this is the case, any reason why it is designed like that, a bit not easy to understand. For grpc or hosted service, we at least need to specify the class (services.AddGrpcClient/services.AddHostedService) to handle it, but why not the open api controller?
Upvotes: 0
Views: 102