How convert this C# function to F# function

Viewed 170

I am passing some code from C # to F # and I come across the following extension method that adds some mongo settings.

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.

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'.

Known type of argument: (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#?

Thanks for reading, I'm new to F#

1 Answers

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.

Related