Skip to content

Provides Options<T> that can update values to source JSON file

License

Notifications You must be signed in to change notification settings

nogic1008/WritableOptions.Net

Repository files navigation

WritableOptions.Net

Provides Options<T> that can update values to source JSON file

NuGet GitHub release .NET CI codecov CodeFactor License

This is a fork of Awesome.Net.WritableOptions, but:

See also: How to update values into appsetting.json?

Usage

This library is intended for use with .NET Generic Host context.

Setup

using Nogic.WritableOptions;

// Load config from { "MySection": {(here)} }
IConfigurationSection section = context.Configration.GetSection("MySection");

// Save & Load from appsettings.json (from root folder)
services.ConfigureWritable<MyOptions>(section);

// Save & Load from (Special Folder)/appsettings.json.
// It is useful for Xamarin
services.ConfigureWritableWithExplicitPath<AppOption>(section, FileSystem.AppDataDirectory);

Consume

public class AppBase
{
    private readonly IWritableOptions<MyOptions> _writableOptions;

    // Constructor DI
    public AppBase(IWritableOptions<MyOptions> writableOptions)
      => _writableOptions = writableOptions;

    public void Run()
    {
        // Read value via IOptions<T>
        var option = _writableOptions.Value;

        // Write value via IWritableOptions<T>
        var newOption = new MyOptions();
        _writableOptions.Update(newOption, reload: true);
    }
}

Sample