web-dev-qa-db-fra.com

Impossible de résoudre le service pour le type «Swashbuckle.AspNetCore.Swagger.ISwaggerProvider»

Je démarre une nouvelle API Web Core et je voudrais ajouter Swagger à mon application.

Mon environnement actuel:

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

Voici mon Startup.cs classe et configuration:

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();
        });
    }

Lorsque j'exécute mon application, j'obtiens l'erreur suivante:

InvalidOperationException: impossible de résoudre le service pour le type "Swashbuckle.AspNetCore.Swagger.ISwaggerProvider" lors de la tentative d'appel du middleware "Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware".

Voici le Stacktrace:

System.InvalidOperationException: impossible de résoudre le service pour le type "Swashbuckle.AspNetCore.Swagger.ISwaggerProvider" lors de la tentative d'appel du middleware "Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware". sur Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.GetService (IServiceProvider sp, Type type, Type middleware) sur lambda_method (Closure, Object, HttpContext, IServiceProvider) sur Microsoft.AspNetCore.Builder.UseMiddlewareExtensions. <> c__DpContext Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.Invoke (contexte HttpContext, ICorsPolicyProvider corsPolicyProvider) sur Microsoft.AspNetCore.Builder.UseMiddlewareExtensions. <> C__DisplayClass4_1.b__2 (HttpContextSoftwareContext

Il est assez clair que je manque quelque chose ici, je ne sais pas exactement quoi. Toute aide serait appréciée.

2
monstertjie_za

Un appel à

services.AddSwaggerGen();

semble être manquant dans le 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;
}

Source

ce qui ajoute le ISwaggerProvider à la collection de services

Vous pouvez refactoriser votre code actuel pour

//...

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

//...

qui, vu par le code source, appellera finalement ConfigureSwaggerGen avec l'action de configuration.

1
Nkosi