我的 Startup.cs 文件中有以下代码来获取和处理我的每个 API 版本描述并将它们添加到我的 Swagger。
var apiVersionDescriptionProvider = services.BuildServiceProvider().GetService<IApiVersionDescriptionProvider>();
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(setup =>
{
foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
{
setup.SwaggerDoc(
$"MyAPISpecification{description.GroupName}",
new OpenApiInfo()
{
Title = "My API Specification",
Version = description.ApiVersion.ToString(),
});
}
我的理解是,我应该依赖注入IApiVersionDescriptionProvider的实现,而不是在我的启动类的ConfigureServices方法中使用BuildServiceProvider,因为这会阻止创建单例的额外副本。
在这个特定示例中,我将如何执行此操作,因为这是配置服务的方法,因此到目前为止我没有构建的实例,该服务可以使用构建服务提供程序。
我在 StackOverflow 的其他地方读到了关于使用选项的信息,但我看不出该示例在这种情况下如何应用。任何帮助将不胜感激,因为此 Swagger 配置基于 2019 年底发布的 Pluralsight 视频,我本以为该视频是正确的。
提前谢谢。
您可以使用实现 IConfigureOptions 接口。有一个示例可以完全执行您在存储库中尝试执行的操作:
namespace Microsoft.Examples
{
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
/// <summary>
/// Configures the Swagger generation options.
/// </summary>
/// <remarks>This allows API versioning to define a Swagger document per API version after the
/// <see cref="IApiVersionDescriptionProvider"/> service has been resolved from the service container.</remarks>
public class ConfigureSwaggerOptions : IConfigureOptions<SwaggerGenOptions>
{
readonly IApiVersionDescriptionProvider provider;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigureSwaggerOptions"/> class.
/// </summary>
/// <param name="provider">The <see cref="IApiVersionDescriptionProvider">provider</see> used to generate Swagger documents.</param>
public ConfigureSwaggerOptions( IApiVersionDescriptionProvider provider ) => this.provider = provider;
/// <inheritdoc />
public void Configure( SwaggerGenOptions options )
{
// add a swagger document for each discovered API version
// note: you might choose to skip or document deprecated API versions differently
foreach ( var description in provider.ApiVersionDescriptions )
{
options.SwaggerDoc( description.GroupName, CreateInfoForApiVersion( description ) );
}
}
static OpenApiInfo CreateInfoForApiVersion( ApiVersionDescription description )
{
var info = new OpenApiInfo()
{
Title = "Sample API",
Version = description.ApiVersion.ToString(),
Description = "A sample application with Swagger, Swashbuckle, and API versioning.",
Contact = new OpenApiContact() { Name = "Bill Mei", Email = "bill.mei@somewhere.com" },
License = new OpenApiLicense() { Name = "MIT", Url = new Uri( "https://opensource.org/licenses/MIT" ) }
};
if ( description.IsDeprecated )
{
info.Description += " This API version has been deprecated.";
}
return info;
}
}
}
它在Startup.cs
中添加为:
services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
参考:ASP.NET 核心/ASP.NET API 版本控制中的选项模式