Allows loading configuration data from a Windows Registry key.
Install-Package TBC.Common.Configuration.Registry
dotnet add package TBC.Common.Configuration.Registry
<PackageReference Include="TBC.Common.Configuration.Registry" Version="2.1.0" />
public static class Program
{
// ...
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.ConfigureAppConfiguration((builderContext, config) =>
{
if (OperatingSystem.IsWindows())
{
config.AddWindowsRegistry(@"SOFTWARE\MyCompany\MyApp");
}
});
}
var builder = WebApplication.CreateBuilder(args);
if (OperatingSystem.IsWindows())
{
builder.Configuration.AddWindowsRegistry(@"SOFTWARE\MyCompany\MyApp");
}
// ...
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\Software\MyCompany]
[HKEY_LOCAL_MACHINE\Software\MyCompany\MyApp]
[HKEY_LOCAL_MACHINE\Software\MyCompany\MyApp\MyConfig]
; Numbers in .REG files can only be hexadecimal
[HKEY_LOCAL_MACHINE\Software\MyCompany\MyApp\MyConfig\DefaultConnection]
"ConnectionString"="Server=example.com; Integrated Security=True; Database=MyDB"
"Provider"="System.Data.SqlClient"
"TimeoutSeconds"=dword:00000078
[HKEY_LOCAL_MACHINE\Software\MyCompany\MyApp\MyConfig\MyWebService]
"Url"="https://example.com/myapi"
"ApiKey"="VGVzdFNlcnZpY2U="
[HKEY_LOCAL_MACHINE\Software\MyCompany\MyApp\MyConfig\MyUsers]
; Example: array/list/collection values
[HKEY_LOCAL_MACHINE\Software\MyCompany\MyApp\MyConfig\MyUsers\0]
@="User1"
[HKEY_LOCAL_MACHINE\Software\MyCompany\MyApp\MyConfig\MyUsers\1]
@="User2"
[HKEY_LOCAL_MACHINE\Software\MyCompany\MyApp\MyConfig\MyUsers\2]
@="User3"
Create an IOptions<T>
implementation:
public class MyConfigOptions : IOptions<MyConfigOptions>
{
public MyConfigOptions Value => this;
public DatabaseConfig DefaultConnection { get; set; }
public WebServiceConfig MyWebService { get; set; }
public List<string> MyUsers { get; set; }
}
public record DatabaseConfig
{
public string ConnectionString { get; set; }
public string Provider { get; set; }
public int TimeoutSeconds { get; set; }
}
public record WebServiceConfig
{
public string Url { get; set; }
public string ApiKey { get; set; }
}
Register options in Startup.ConfigureServices()
method:
services.AddOptions<MyConfigOptions>().BindConfiguration("MyConfig");
Now you can inject IOptions<MyConfigOptions>
into transient services and IOptionsMonitor<MyConfigOptions>
into singleton ones.