C
C#3mo ago
Core

✅ .NET Worker service doesn't load appsettings.json into a class

Hello, I am trying to load configuration values into a class or record, but it doesn't work. The properties remain null. I do the following:
c#
builder.Services.Configure<DnsRecordOptions>(builder.Configuration.GetSection("DnsRecords"));
c#
builder.Services.Configure<DnsRecordOptions>(builder.Configuration.GetSection("DnsRecords"));
c#
"DnsRecords:": {
"ARecord": "0.0.0.0",
},
c#
"DnsRecords:": {
"ARecord": "0.0.0.0",
},
c#
public record DnsRecordOptions
{
public required string ARecord { get; init; }
}
c#
public record DnsRecordOptions
{
public required string ARecord { get; init; }
}
Loading config values this way works in a Web API project, but I don't understand why it wouldn't in an other type of project. I've also added the DnsRecords configuration to appsettings.json and appsetting.Development.json, but the outcome was the same.
No description
8 Replies
Becquerel
Becquerel3mo ago
what does your Program.cs look like? is it using Host.CreateDefaultBuilder()? is builder.Configuration.GetSection returning the actual 0.0.0.0 value? also, is your appsettings.json set to copy on build?
Core
Core3mo ago
No, it's using the Host.CreateApplicationBuilder()
c#
var builder = Host.CreateApplicationBuilder(args);

builder.ConfigureOptions();

var host = builder.Build();
host.Run();
c#
var builder = Host.CreateApplicationBuilder(args);

builder.ConfigureOptions();

var host = builder.Build();
host.Run();
c#
public static class OptionsConfigurationExtension
{
public static void ConfigureOptions(this HostApplicationBuilder builder)
{
builder.Services.Configure<DnsRecordOptions>(builder.Configuration.GetSection("DnsRecords"));
}
}
c#
public static class OptionsConfigurationExtension
{
public static void ConfigureOptions(this HostApplicationBuilder builder)
{
builder.Services.Configure<DnsRecordOptions>(builder.Configuration.GetSection("DnsRecords"));
}
}
No, there is no extra configuration. Everything is how the default Program.cs was generated
Becquerel
Becquerel3mo ago
what i mean is, your appsettings.json should be set to copy on build is it present in the /bin/ folder when you compile your app? this all looks fine, so i am wondering if the appsettings.json is missing somehow
Core
Core3mo ago
no, because also access other configs before build, like this builder.Configuration["MessageBroker:Host"] and it gets the values so the appsettings,json must have been copied wow..... I am an idiot.
c#
"DnsRecords:": {
"ARecord": "0.0.0.0",
},
c#
"DnsRecords:": {
"ARecord": "0.0.0.0",
},
There is an extra : in the config name.... Everything works fine :))
Becquerel
Becquerel3mo ago
haha classic well, glad you found it 🙂
Core
Core3mo ago
Thanks for helping me
Batuhan
Batuhan3mo ago
$close
MODiX
MODiX3mo ago
If you have no further questions, please use /close to mark the forum thread as answered
Want results from more Discord servers?
Add your server