All checks were successful
Caddy Manager CI build / docker (push) Successful in 6m37s
Preserve configuration defaults with the .NET 10 binder and update dependencies, Docker builds, CI, and test tooling.
36 lines
1.3 KiB
C#
36 lines
1.3 KiB
C#
using NetCore.AutoRegisterDi;
|
|
using Microsoft.Extensions.Configuration;
|
|
using CaddyManager.Contracts.Configurations;
|
|
|
|
namespace CaddyManager.Services.Configurations;
|
|
|
|
/// <inheritdoc />
|
|
[RegisterAsSingleton]
|
|
public class ConfigurationsService(IConfiguration configuration) : IConfigurationsService
|
|
{
|
|
/// <inheritdoc />
|
|
public T Get<T>() where T : class
|
|
{
|
|
var section = typeof(T).Name;
|
|
|
|
// Have the configuration section name be the section name without the "Configurations" suffix
|
|
if (section.EndsWith("Configurations"))
|
|
section = section[..^"Configurations".Length];
|
|
else if (section.EndsWith("Configuration"))
|
|
section = section[..^"Configuration".Length];
|
|
|
|
var result = configuration.GetSection(section).Get<T>();
|
|
var defaults = Activator.CreateInstance<T>();
|
|
|
|
if (result is null) return defaults;
|
|
|
|
// The .NET 10 binder writes nulls over property initialisers, so put the defaults back
|
|
foreach (var property in typeof(T).GetProperties())
|
|
{
|
|
if (property is { CanRead: true, CanWrite: true } && property.GetValue(result) is null)
|
|
property.SetValue(result, property.GetValue(defaults));
|
|
}
|
|
|
|
return result;
|
|
}
|
|
} |