【问题标题】:Unable to resolve service for type 'Swashbuckle.AspNetCore.Swagger.ISwaggerProvider'无法解析“Swashbuckle.AspNetCore.Swagger.ISwaggerProvider”类型的服务
【发布时间】:2020-03-13 12:25:58
【问题描述】:

我正在启动一个新的Core Web API,并希望将Swagger 添加到我的应用程序中。

我现在的环境:

  • .Net Core 3.0
  • Swashbuckle.AspNetCore 5.0.0-rc4

这是我的Startup.cs 类和配置:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();

        //AK: Enable CORS
        //CORS should be configured on host server.
        services.AddCors(setupAction =>
        {
            setupAction.AddPolicy(DevCorsPolicyName,
                builder =>
                {
                    builder.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
                });
        });

        #region Configuration

        //Configuration File
        services.Configure<AppSettingConfiguration>(Configuration.GetSection("AppSettings"));
        //AutoMapper
        services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

        //Configure Swagger
        services.ConfigureSwaggerGen(c =>
        {
            c.SwaggerDoc("v3", new OpenApiInfo
            {
                Title = "GTrackAPI",
                Version = "v3"
            });
        });

        #endregion

        #region Dependency Injection

        //Database context and repository
        services.AddDbContext<IGTrackContext, GTrackContext>(builder =>
        {
            builder.UseSqlServer(connectionString: Configuration.GetConnectionString("gtrackConnection"), sqlServerOptionsAction: null);
        });
        services.AddScoped<IGTrackRepository, GTrackRepository>();

        //facade layers
        services.AddScoped<IPersonFacade, PersonFacade>();

        //Service layers
        services.AddScoped<IPersonService, PersonService>();

        #endregion
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //Enable development environment only settings
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        //AK: Only allow all origins for development environmnet
        app.UseCors(DevCorsPolicyName);

        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("/swagger/v1/swagger.json", "GTrackAPI");
            c.RoutePrefix = string.Empty; //Configures swagger to load at application root
        });

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

当我运行我的应用程序时,我收到以下错误:

InvalidOperationException:尝试调用中间件“Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware”时,无法解析“Swashbuckle.AspNetCore.Swagger.ISwaggerProvider”类型的服务。

这里是Stacktrace

System.InvalidOperationException:尝试调用中间件“Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware”时,无法解析“Swashbuckle.AspNetCore.Swagger.ISwaggerProvider”类型的服务。 在 Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.GetService(IServiceProvider sp, Type type, Type middleware) 在 lambda_method(闭包,对象,HttpContext,IServiceProvider) 在 Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.c__DisplayClass4_1.b__2(HttpContext 上下文) 在 Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke(HttpContext 上下文,ICorsPolicyProvider corsPolicyProvider) 在 Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.c__DisplayClass4_1.b__2(HttpContext 上下文) 在 Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

很明显,我在这里遗漏了一些东西,不确定到底是什么。任何帮助将不胜感激。

【问题讨论】:

    标签: c# asp.net-core dependency-injection swagger asp.net-core-webapi


    【解决方案1】:

    来电

    services.AddSwaggerGen();
    

    ConfigureServices 中似乎缺少。

    public static IServiceCollection AddSwaggerGen(
        this IServiceCollection services,
        Action<SwaggerGenOptions> setupAction = null)
    {
        // Add Mvc convention to ensure ApiExplorer is enabled for all actions
        services.Configure<MvcOptions>(c =>
            c.Conventions.Add(new SwaggerApplicationConvention()));
    
        // Register generator and it's dependencies
        services.AddTransient<ISwaggerProvider, SwaggerGenerator>();
        services.AddTransient<ISchemaGenerator, SchemaGenerator>();
        services.AddTransient<IApiModelResolver, JsonApiModelResolver>();
    
        // Register custom configurators that assign values from SwaggerGenOptions (i.e. high level config)
        // to the service-specific options (i.e. lower-level config)
        services.AddTransient<IConfigureOptions<SwaggerGeneratorOptions>, ConfigureSwaggerGeneratorOptions>();
        services.AddTransient<IConfigureOptions<SchemaGeneratorOptions>, ConfigureSchemaGeneratorOptions>();
    
        // Used by the <c>dotnet-getdocument</c> tool from the Microsoft.Extensions.ApiDescription.Server package.
        services.TryAddSingleton<IDocumentProvider, DocumentProvider>();
    
        if (setupAction != null) services.ConfigureSwaggerGen(setupAction);
    
        return services;
    }
    

    这就是将ISwaggerProvider 添加到服务集合的原因

    您可以将当前代码重构为

    //...
    
    //Configure Swagger
    services.AddSwaggerGen(c => { //<-- NOTE 'Add' instead of 'Configure'
        c.SwaggerDoc("v3", new OpenApiInfo {
            Title = "GTrackAPI",
            Version = "v3"
        });
    });
    
    //...
    

    从源代码中可以看出,它最终会通过设置操作调用ConfigureSwaggerGen

    【讨论】:

      【解决方案2】:

      如果您使用 dotnet CLI 创建了 Web API,并且遇到此错误

      错误 NU1100:无法为“net5.0”解析“Swashbuckle.AspNetCore (>= 5.6.3)”

      表示dotnet CLI找不到swagger依赖

      要解决此问题,您可以运行以下 dotnet CLI 命令

      dotnet add package Swashbuckle.AspNetCore.Swagger --version 5.6.3
      

      【讨论】:

        【解决方案3】:

        Minimal API 和 .NET 6 的答案

        1. 安装Swashbuckle.AspNetCore NuGet 包
        2. AddSwaggerGen之前添加AddEndpointsApiExplorer

        工作示例:

        var builder = WebApplication.CreateBuilder(args);
        
        var services = builder.Services;
        services.AddEndpointsApiExplorer();
        services.AddSwaggerGen();
        
        var app = builder.Build();
        
        if (app.Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        
        app.UseSwagger();
        
        app.MapGet("/", () => "Hello World!");
        
        app.UseSwaggerUI();
        app.Run();
        
        

        【讨论】:

        • 谢谢。即将升级到 .NET 6,将查看您的解决方案
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-16
        • 2022-01-10
        • 2019-02-10
        • 2019-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多