带F#的Swashbuckle:System.InvalidOperationException:'无法找到所需的服务

时间:2019-01-11 04:31:25

标签: c# asp.net-core f# swashbuckle

我用C#创建了一个新的ASP.NET Core Web Application,然后跟随Get started with Swashbuckle and ASP.NET Core。效果很好。

我在F#中做了同样的事情,然后遇到了这个问题:

System.InvalidOperationException: 'Unable to 
find the required services. Please add all 
the required services by calling 
'IServiceCollection.AddMvc' inside the call 
to 'ConfigureServices(...)' in the 
application startup code.'

这是Startup.fs

namespace ASPNETSwagger

open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Configuration
open Microsoft.Extensions.DependencyInjection
open Swashbuckle.AspNetCore.Swagger

type Startup () =
    new (configuration: IConfiguration) as this =
        Startup() then
        this.Configuration <- configuration

    member _this.ConfigureServices(services: IServiceCollection) =
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2) |> ignore
        services.AddSwaggerGen(fun c -> c.SwaggerDoc("v1", new Info(Title = "My API", Version = "v1")))

    member this.Configure(app: IApplicationBuilder, env: IHostingEnvironment) =
        app.UseSwagger() |> ignore
        app.UseSwaggerUI(fun c -> c.SwaggerEndpoint("swagger/v1/swagger.json", "My API V1")) |> ignore

        if (env.IsDevelopment()) then
            app.UseDeveloperExceptionPage() |> ignore
        else
            app.UseHsts() |> ignore

        app.UseHttpsRedirection() |> ignore
        app.UseMvc() |> ignore

    member val Configuration : IConfiguration = null with get, set

我该如何解决?

1 个答案:

答案 0 :(得分:0)

services.AddSwaggerGen(fun c -> c.SwaggerDoc("v1", new Info(Title = "My API", Version = "v1")))

是一个返回IServiceCollection的表达式。包含方法ConfigureServices需要返回unit。因此,在该行的末尾添加|> ignore或在最后一行添加()可以修复签名。

此外,此行

app.UseSwaggerUI(fun c -> c.SwaggerEndpoint("swagger/v1/swagger.json", "My API V1")) |> ignore

需要成为

app.UseSwaggerUI(fun c -> c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1")) |> ignore

它缺少前导/