matteobortolazzo / dotnet-options-generator

Generate and register IOptions from appsettings.json at compile-time with source generators.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Downloads

OptionsGenerator

Generate and register IOptions from appsettings.json at compile-time with C# source generators.

Getting started

public partial class Startup { .... }
  • In ConfigureServices add RegisterOptions(services);:
public void ConfigureServices(IServiceCollection services)
{
    ...
    RegisterOptions(services);
    ...
}
  • If not there already, create a Configuration property:
public IConfiguration Configuration { get; }
  • In the .csproj add the following:
<ItemGroup>
    <AdditionalFiles Include="appsettings.json" />
</ItemGroup>
  • Add objects to appsettings.json:
{
  "MyOtherOptions": {
    "MyString": "any",
    "MyInt": 1,
    "MyDouble": 1.1,
    "MyBool": true,
    "MyObject": {
      "MyObjectString": "any"
    },
    "MyArray": [ "any" ]
  }
}
  • Inject IOptions<>. Any change to appsettings.json will recreated the classes at compile time.
public TodoController(
    ILogger<TodoController> logger,
    IOptions<MyOtherOptions> options)
{
    ...
}

How it works

  1. The generator parse appsettings.json;
  2. For each objects in the root it creates an equivalent C# class.
  3. Creates Startup.Generated.cs partial class with a private method RegisterOptions.
  4. Inside the method, it adds a call to services.Configure.

About

Generate and register IOptions from appsettings.json at compile-time with source generators.

License:MIT License


Languages

Language:C# 100.0%