If the purpose is for generation outside the code and various issues are preventing it from loading correctly, you could create another entrypoint with the simplest version of the application to provide what the swagger generator needs like this:
public static class SwaggerGen
{
public static bool EntryPointForSwaggerGenerationApplication(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
if (Assembly.GetEntryAssembly()?.GetName().Name == "dotnet-swagger")
{
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var appForGen = builder.Build();
appForGen.UseSwagger();
appForGen.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1/swagger.json", Names.ApplicationName);
});
appForGen.Run();
return true;
}
return false;
}
}
Then the start of your program could look like this:
if (SwaggerGen.EntryPointForSwaggerGenerationApplication(args))
return;
This will allow swagger generation to run from dotnet swagger tofile
and only enter this small application that allows it to access what it needs.