为什么不将 Swagger 服务有条件地添加到 DI 容器中(仅在开发中)?

Why aren't Swagger services added to DI container conditionally (only in development)?

ASP.NETCore WebAPI默认模板如下

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

// Why are the following two statements not enabled only in development?
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// Others are removed for the sake of simplicity.

app.Run();

如您所见,UseSwagger()UseSwaggerUI() 仅在开发中激活。

问题

我很好奇为什么 AddEndpointsApiExplorer()AddSwaggerGen() 也只在开发中不被激活。

What's new in ASP.NET Core 5.0中,您可以看到配置注入IWebHostEnvironment

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json",
                         "WebApp1 v1"));
    }
          ...
 }

在 .net6 中,从 Use multiple environments in ASP.NET Core默认 ASP.NET 核心网络应用程序模板调用 WebApplication.CreateBuilder。 ASPNETCORE_ENVIRONMENT 值覆盖 DOTNET_ENVIRONMENT.

var builder = WebApplication.CreateBuilder(args);   
 ...  
var app = builder.Build();
// Configure the HTTP request pipeline
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

一般来说,配置可能是处理基于环境的不同行为的一种简单且更直观的途径。所以你不需要有条件的给DI容器添加Swagger服务。

然而依赖注入容器也是切换服务的好点。 您可以使用以下代码有条件地将 Swagger 服务添加到 DI 容器。

builder.Services.AddEndpointsApiExplorer();

if(builder.Environment.IsDevelopment())
{
    builder.Services.AddSwaggerGen();
}

结果: