3

I'm building a small project to understand F# better. As part of it, I want a function "myAppSettings" that uses System.Configuration.ConfigurationManager to read settings from the AppSettings.config file. I put this in a separate file in my solution called myAppSettings and it looks like this:

namespace foo.bar
open System
open System.Configuration

module myAppSettings =
    let read key mandatory = 
        let appSettings = ConfigurationManager.AppSettings
        let value = appSettings key
        if mandatory && String.IsNullOrEmpty(value) then
            failwith "bad hombres"
        value

This does not compile however, I get the error:

Error 1 The namespace or module 'ConfigurationManager' is not defined

I know that that object is in System.Configuration (use it all the time from C#) so I must have syntax wrong somewhere, but where?

I also tried:

let appSettings = new ConfigurationManager.AppSettings
let value = appSettings key

which then found the ConfigurationManager (the new keyword helped) but then objected to the "let value":

Error 1 Incomplete structured construct at or before this point in expression

I want to understand the two error messages and the right way to access the settings in the app.config file.

user1443098
  • 6,487
  • 5
  • 38
  • 67
  • This question isn't about `ConfigurationManager` not being available in the current context, it is about accessing `ConfigurationManager` from F#. – Sven Grosen Mar 14 '17 at 21:46

1 Answers1

4

Your problem is with how you are accessing the ConfigurationManager:

namespace foo.bar
open System
open System.Configuration

module myAppSettings =
    let read key mandatory = 
        //let appSettings = ConfigurationManager.AppSettings
        //let value = appSettings key
        let value = ConfigurationManager.AppSettings.Item(key)
        if mandatory && String.IsNullOrEmpty(value) then
            failwith "bad hombres"
        value

If you want to keep the two-part access, try it like this:

let appSettings = ConfigurationManager.AppSettings
let value = appSettings.Item(key)
Sven Grosen
  • 5,616
  • 3
  • 30
  • 52