Generate and register IOptions
from appsettings.json
at compile-time with C# source generators.
- Install it from NuGet: https://www.nuget.org/packages/OptionsGenerator/0.1.0-preview
- Make
Startup
a partial class:
public partial class Startup { .... }
- In
ConfigureServices
addRegisterOptions(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 toappsettings.json
will recreated the classes at compile time.
public TodoController(
ILogger<TodoController> logger,
IOptions<MyOtherOptions> options)
{
...
}
- The generator parse
appsettings.json
; - For each objects in the root it creates an equivalent C# class.
- Creates
Startup.Generated.cs
partial class with a private methodRegisterOptions
. - Inside the method, it adds a call to
services.Configure
.