简体   繁体   English

如何将此 C# function 转换为 F# ZC1C425268E68385D14AB5074C17A9

[英]How convert this C# function to F# function

I am passing some code from C # to F # and I come across the following extension method that adds some mongo settings.我正在将一些代码从 C # 传递到 F #,我遇到了以下扩展方法,它添加了一些 mongo 设置。

public static class Container
    {
        public static IServiceCollection AddServicesFromInfrastructure(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure<MongoDBSettings>(configuration.GetSection(nameof(MongoDBSettings)));
            services.AddSingleton<IMongoDBSettings>(sp => sp.GetRequiredService<IOptions<MongoDBSettings>>().Value);
            return services;
        }
    }

I have the following transformation and everything is fine, the problem is in the lambda that goes inside the AddSingleton method.我进行了以下转换,一切都很好,问题出在 AddSingleton 方法内部的 lambda 中。

module Extensions =    

    type IServiceCollection with
        member this.AddMongoDBConfiguration(configuration: IConfiguration) =
            this.Configure<MongoDBSettings>(configuration.GetSection("MongoDBSettings")) |> ignore
            this.AddSingleton<IMongoDBSettings>(fun sp -> sp.GetRequiredService<IOptions<MongoDBSettings>>().Value) |> ignore
            this

This line return me the error:此行返回错误:

No overloads match for method 'AddSingleton'.方法“AddSingleton”没有重载匹配。

Known type of argument: (IServiceProvider -> MongoDBSettings)已知参数类型:(IServiceProvider -> MongoDBSettings)

this.AddSingleton<IMongoDBSettings>(fun sp -> sp.GetRequiredService<IOptions<MongoDBSettings>>().Value) |> ignore

What is the correct way to convert that lambda function to F#?将 lambda function 转换为 F# 的正确方法是什么?

Thanks for reading, I'm new to F#感谢阅读,我是 F# 的新手

Try calling this way:尝试这样调用:

module Extensions =    

    type IServiceCollection with
        member this.AddMongoDBConfiguration(configuration: IConfiguration) =
            this.Configure<MongoDBSettings>(configuration.GetSection("MongoDBSettings")) |> ignore
            this.AddSingleton<IMongoDBSettings>(Func<_,_>(fun (sp: IServiceProvider) -> 
                sp.GetRequiredService<IOptions<MongoDBSettings>>().Value :> IMongoDBSettings)) |> ignore
            this

So you need to convert F# function to System.Func (you also need to open System namespace by the way), annotate the type of parameter ( sp: IServiceProvider ) and up-cast result to interface IMongoDBSettings by using :> operator, since F# does not implicitly do such conversions. So you need to convert F# function to System.Func (you also need to open System namespace by the way), annotate the type of parameter ( sp: IServiceProvider ) and up-cast result to interface IMongoDBSettings by using :> operator, since F#不会隐式进行此类转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM