0

I want to read a simple connection string from the appsettings.json file in F#

  "ConnectionStrings": {
    "myConnectionString": "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;"
  }

In C# I could use the read the connection string with an object from a class implementing the Iconfiguration provided in the constructor. But in the F# web API with .net 6, I couldn't find anything that made me read the connection string section or an other key in from the AppSettings.json file

Here is an example how I could read from the Appsettings.json in C# .net 6 Web API. This is what I want to do.

public class TestModel : PageModel
{
    // requires using Microsoft.Extensions.Configuration;
    private readonly IConfiguration _configuration;

    public TestModel(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void Connect()
    {
      var connectionString = _config.GetConnectionString("myConnectionString");
      // Do Something with the string
    }
}
1
  • What does your F# code look like at the moment? Did you start from a template? Which one? Sep 25, 2022 at 14:36

1 Answer 1

0

The F# implementation of the Web API project is very similar to the C# one. In order to use the configuration in one of your classes you just need to inject the IConfiguration parameter to the constructor of your class. The default bootstrap code takes care of setting up the dependency injection for the configuration framework.

I created a sample Web API project for F# and injected the IConfiguration to the controller:

namespace WebApiTest.Controllers

open System
open System.Collections.Generic
open System.Linq
open System.Threading.Tasks
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Logging
open Microsoft.Extensions.Logging
open WebApiTest
open Microsoft.Extensions.Configuration

[<ApiController>]
[<Route("[controller]")>]
type WeatherForecastController (logger : ILogger<WeatherForecastController>, configuration: IConfiguration) =
    inherit ControllerBase()

    let summaries =
        [|
            "Freezing"
            "Bracing"
            "Chilly"
            "Cool"
            "Mild"
            "Warm"
            "Balmy"
            "Hot"
            "Sweltering"
            "Scorching"
        |]

    [<HttpGet>]
    member _.Get() =
        let cstr = configuration.GetConnectionString("MyConnectionString")
        logger.LogInformation($"Connection string: {cstr}")
        let rng = System.Random()
        [|
            for index in 0..4 ->
                { Date = DateTime.Now.AddDays(float index)
                  TemperatureC = rng.Next(-20,55)
                  Summary = summaries.[rng.Next(summaries.Length)] }
        |]

As you see, the configuration parameter injected in the constructor is accessible as a private member variable in the Get() method. I just log the connection string to illustrate that the code works as expected. Here's my appsettings.json:

{
  "ConnectionStrings": {
    "MyConnectionString": "SampleConnectionString"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.