长话短说,当我使用类似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>
}
答案 0 :(得分:3)
由于上面的注释,解决方案只是将[<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>()