Configuration
SwiftlyS2's configuration system lets your plugin create config files, bind typed models, and reload settings at runtime, through APIISwiftlyCore.Configuration (APIIPluginConfigurationService).
Service Members
Type is the type of the property, or the return type of the method:
| Member | Type | Description |
|---|---|---|
| APIIPluginConfigurationService.BasePath | string | Base path of the plugin's configuration files |
| APIIPluginConfigurationService.BasePathExists | bool | Whether BasePath exists in the file system |
| APIIPluginConfigurationService.GetConfigPath | string | Path of a file inside BasePath, for (string name) with the extension included in name |
| APIIPluginConfigurationService.Manager | IConfigurationManager | The configuration manager the service is backed by |
| APIIPluginConfigurationService.InitializeWithTemplate | APIIPluginConfigurationService | Initializes a file from a packaged template, for (string name, string templateName) |
| APIIPluginConfigurationService.InitializeJsonWithModel | APIIPluginConfigurationService | Initializes a JSON file from a model, for (string name, string sectionName) and (string name, string sectionName, bool addMissingKeys) |
| APIIPluginConfigurationService.InitializeTomlWithModel | APIIPluginConfigurationService | Initializes a TOML file from a model, for (string name, string sectionName) and (string name, string sectionName, bool addMissingKeys) |
| APIIPluginConfigurationService.Configure | APIIPluginConfigurationService | Configures the internal manager, for (Action<IConfigurationBuilder> configure) |
Every method returns APIIPluginConfigurationService, so calls chain.
Paths
string basePath = Core.Configuration.BasePath;
bool exists = Core.Configuration.BasePathExists;
string configPath = Core.Configuration.GetConfigPath("config.jsonc"); // needs the extensionSee APIIPluginConfigurationService.BasePath, APIIPluginConfigurationService.BasePathExists and APIIPluginConfigurationService.GetConfigPath.
Initializing Config Files
// From a packaged templates/ folder
Core.Configuration.InitializeWithTemplate("config.jsonc", "config.template.jsonc");
// From a typed model - creates the file with defaults if it doesn't exist yet
Core.Configuration.InitializeJsonWithModel<MainConfig>("config.jsonc", "Main");
Core.Configuration.InitializeTomlWithModel<DatabaseConfig>("database.toml", "Database");APIIPluginConfigurationService.InitializeWithTemplate takes (name, templateName) and initializes name from templateName, which must be packaged in a templates/ folder inside your plugin.
APIIPluginConfigurationService.InitializeJsonWithModel and APIIPluginConfigurationService.InitializeTomlWithModel take (name, sectionName) and write the file from the model's defaults, using sectionName as the section the options are later bound to. T must be a class with a parameterless constructor (where T : class, new()).
Properties and fields marked with [Description] are written with the description as a comment above the key:
- JSON:
//comment lines in a.jsoncfile, for members of nested objects, list items and dictionary values as well. A.jsonfile is always written as plain JSON, because comments are not valid JSON. - TOML:
#comment lines above the key, or above the table header. Members of inline tables cannot carry comments.
using System.ComponentModel;
public class DatabaseConfig
{
[Description("Host name of the database server.")]
public string Host { get; set; } = "127.0.0.1";
[Description("Port of the database server.")]
public int Port { get; set; } = 3306;
}Adding Missing Keys
Both model initializers have an extra overload taking addMissingKeys, for filling in keys added to the model after the file was first written:
Core.Configuration.InitializeJsonWithModel<MainConfig>("config.jsonc", "Main", addMissingKeys: true);
Core.Configuration.InitializeTomlWithModel<DatabaseConfig>("database.toml", "Database", addMissingKeys: true);They behave like the overloads without addMissingKeys when the file does not exist yet. When the file exists and addMissingKeys is true, keys present in the model but missing from the file are inserted with their default value, including keys of nested objects. Keys are matched case-insensitively, the same way the configuration binder reads them. Everything else in the file, including existing values, comments and formatting, is left untouched.
- JSON: each inserted key gets its
[Description]as//comment lines above it in a.jsoncfile. Dictionary entries and list items are never added, and a file that is not valid JSON is not changed. - TOML: keys missing from a table are inserted after the table's last value, and tables missing from the file are appended at its end, each with its
[Description]as#comment lines. Members of inline tables and entries of table arrays are never added, and a file that is not valid TOML is not changed.
Registering Config Sources
See APIIPluginConfigurationService.InitializeWithTemplate, APIIPluginConfigurationService.InitializeJsonWithModel and APIIPluginConfigurationService.InitializeTomlWithModel - all three return APIIPluginConfigurationService, so they chain, followed by APIIPluginConfigurationService.Configure to register the file as a live, reloadable source:
Core.Configuration
.InitializeJsonWithModel<MainConfig>("config.jsonc", "Main")
.InitializeTomlWithModel<DatabaseConfig>("database.toml", "Database")
.Configure(builder =>
{
builder.AddJsonFile(Core.Configuration.GetConfigPath("config.jsonc"), optional: false, reloadOnChange: true);
builder.AddTomlFile(Core.Configuration.GetConfigPath("database.toml"), optional: false, reloadOnChange: true);
});AddJsonFile/AddTomlFile resolve relative to the process's working
directory, not your plugin folder - pass the full path from GetConfigPath,
not a bare file name.
Use APIIPluginConfigurationService.Manager to reach the raw IConfigurationManager directly.
Complete Example
namespace MyPlugin;
public class MainConfig
{
public bool Enabled { get; set; } = true;
public bool Debug { get; set; } = false;
public int MaxPlayers { get; set; } = 32;
}
public class DatabaseConfig
{
public string Host { get; set; } = "127.0.0.1";
public int Port { get; set; } = 3306;
}
public override void Load(bool hotReload)
{
Core.Configuration
.InitializeJsonWithModel<MainConfig>("config.jsonc", "Main")
.InitializeTomlWithModel<DatabaseConfig>("database.toml", "Database")
.Configure(builder =>
{
builder.AddJsonFile(Core.Configuration.GetConfigPath("config.jsonc"), optional: false, reloadOnChange: true);
builder.AddTomlFile(Core.Configuration.GetConfigPath("database.toml"), optional: false, reloadOnChange: true);
});
var services = new ServiceCollection();
services.AddSwiftly(Core);
services.AddOptionsWithValidateOnStart<MainConfig>().BindConfiguration("Main");
services.AddOptionsWithValidateOnStart<DatabaseConfig>().BindConfiguration("Database");
}services.AddSwiftly(Core, addLogger = true, addConfiguration = true) registers APIIPluginConfigurationService, its IConfigurationManager (APIIPluginConfigurationService.Manager) and an IConfiguration resolving to that same manager as singletons - but only when APIIPluginConfigurationService.BasePathExists is true, so pass addConfiguration: false to leave them out. See Dependency Injection for more on services.AddSwiftly(Core).
AddSwiftly also replaces the default options factory with APISwiftlyOptionsFactory`1, so values read from the file replace the model's code defaults instead of merging with them - a list or dictionary in the file replaces the default collection instead of being appended to it. A default collection is only cleared for a key the configuration actually contains, and members are matched by [ConfigurationKeyName], then [JsonPropertyName], then the member name. The factory also runs every IValidateOptions<T> registered in the container and throws OptionsValidationException when one of them fails.
Consume with IOptionsMonitor<T> to react to reloads:
public class ExampleService
{
public ExampleService(IOptionsMonitor<MainConfig> main)
{
main.OnChange(cfg => Console.WriteLine($"Main config reloaded. Enabled: {cfg.Enabled}"));
}
}