C#C
C#3y ago
Dropps

options pattern not working

migrated not so long ago .net 8 did they change something with the options pattern? it seems to not work anymore for some reason that i cant explain myself

see code below:

builder.Services.AddOptions<JwtOptions>(JwtOptions.SectionName)
    .Bind(config.GetSection(JwtOptions.SectionName));

builder.Services.AddOptions<DatabaseConnectionOptions>(DatabaseConnectionOptions.SectionName)
    .Bind(config.GetSection(DatabaseConnectionOptions.SectionName));
    

inside here it should retrive the stuff from the appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=db;Database=postgres;User ID=admin;Password=admin;"
  },
  "Jwt": {
    "Key": "HIDDEN_API_KEY"
  },
  "AllowedHosts": "*"
}


but whenever i hit my AddInfrastructure point i get an error that it would be null see her:

        ...
        // Database
        var options = serviceCollection.BuildServiceProvider().GetRequiredService<IOptions<DatabaseConnectionOptions>>();
        
        if (string.IsNullOrWhiteSpace(options.Value.DefaultConnection))
        {
            throw new InvalidOperationException($"{DatabaseConnectionOptions.SectionName}:{nameof(DatabaseConnectionOptions.DefaultConnection)} cannot be null or whitespace");
        }
        
        serviceCollection.AddDbContext<AppDbContext>(dbOptions =>
        {
            dbOptions.UseNpgsql(options.Value.DefaultConnection);
        });
        
        serviceCollection.AddScoped<IUnitOfWork>(serviceProvider => serviceProvider.GetRequiredService<AppDbContext>());
        
        return serviceCollection;


options classes have similar schema each:

public class DatabaseConnectionOptions
{
    public const string SectionName = "ConnectionStrings";
    
    public string? DefaultConnection { get; set; }
}


someone knows how to fix this?
Was this page helpful?