gpt4 book ai didi

c# - 有没有办法使用 F# 记录类型来提取 appsettings.json 配置?

转载 作者:行者123 更新时间:2023-11-30 15:51:40 25 4
gpt4 key购买 nike

长话短说,当我使用类似 C# 的类时,我可以将 appsettings.json 提取到 Configuration 类型:

type Connection() =
member val Host = Unchecked.defaultof<string> with get,set
member val Port = Unchecked.defaultof<int> with get,set
member val UserName = Unchecked.defaultof<string> with get,set
member val Password = Unchecked.defaultof<string> with get,set

type Configuration() =
member val RabbitMQ = Unchecked.defaultof<Connection> with get,set
member val PostgreSQL = Unchecked.defaultof<Connection> with get,set

let fetchConfiguration =
let builder = (new ConfigurationBuilder())
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.AddEnvironmentVariables();
let configurationRoot = builder.Build();
let configuration = new Configuration()
configurationRoot.Bind(configuration)
configuration

但是当使用 F# 记录类型时:


type Connection = {
Host: string
Port: int32
Username: string
Password: string
}

type Configuration = {
RabbitMQ: Connection
PostgreSQL: Connection
}

let fetchConfiguration =
let builder = (new ConfigurationBuilder())
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.AddEnvironmentVariables();
let configurationRoot = builder.Build();
let configuration = {
RabbitMQ = {
Host = Unchecked.defaultof<string>
Port = Unchecked.defaultof<int>
Username = Unchecked.defaultof<string>
Password = Unchecked.defaultof<string>
}
PostgreSQL = {
Host = Unchecked.defaultof<string>
Port = Unchecked.defaultof<int>
Username = Unchecked.defaultof<string>
Password = Unchecked.defaultof<string>
}
}
configurationRoot.Bind(configuration)
configuration

我最终得到的配置与我在调用“绑定(bind)”方法之前给出的值没有什么不同(即使我没有任何异常),基本上就像什么都没发生一样。

注意:当我使用下面的默认值时,我有相同的行为:

let configuration = {
RabbitMQ = Unchecked.defaultof<Connection>
PostgreSQL = Unchecked.defaultof<Connection>
}

最佳答案

感谢上面的评论,解决方案只是设置 [<CLIMutable>] F# 记录类型的属性:

[<CLIMutable>]
type Connection = {
Host: string
Port: int32
Username: string
Password: string
}

[<CLIMutable>]
type Configuration = {
RabbitMQ: Connection
PostgreSQL: Connection
}

let fetchConfiguration =
let builder = (new ConfigurationBuilder())
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", true, true)
.AddEnvironmentVariables();
let configurationRoot = builder.Build();
configurationRoot.Get<Configuration>()

关于c# - 有没有办法使用 F# 记录类型来提取 appsettings.json 配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56442871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com