Configuration

The Configuration plugin is a server-side plugin required by most other SA plugins. It exposes a IConfiguration interface you can use to expose settings value and settings changes from IEnvironment. In particular, IConfiguration ensures that any component that subscribes to the SettingsChanged event will have the registration properly unregistered at scope closure, preventing memory and resource leaks.

Usage (server)

Enabling the plugin

Install the nuget package Stormancer.Server.Plugins.Configuration in the server application project.

Setting Retrieval

There are two ways to access settings:

  • Settings are exposed as a dynamic object in IConfiguration.Settings. whose structure reflects the configuration as set in the SA config web API.

  • T GetConfigValue<T>(string path,T @default=default) deserializes a settings node into T and return the optional default value if the node does not exist. An exception is thrown if the node in the path cannot be deserialized into T (for instance if T is an object and the node was a json int value, or an array.)

If a config node is missing, the dynamic object returns null on retrieval. Make sure when you use a setting to not expose yourself to a NullReferenceException. Don’t assume any given node is present. Also provide a pertinent default value if the configuration entry is not present. You need to explicitely cast the setting value in the relevant type. If the relevant type is a value type, use a nullable of this type instead and provide a default value.

For instance, instead of using:

cacheDuration = (int)config.Settings.assetsStorage.cacheDuration;

you should use:

cacheDuration = (int?)config.Settings.assetsStorage?.cacheDuration ?? 60;

Note

Going forward, creating a configuration class and using GetConfigValue is the prefered way of accessing configuration settings.

Subscribing to configuration changes

Single instance and instance per scene objets can receive ConfigurationChanged or ActiveDeploymentChanged events by implementing IConfigurationChangedEventHandler. To be notified, the object must be registered in the dependency container as exposing the IConfigurationChangedEventHandler contract. For instance, to register the class MyClass as both exposing the contract IConfigurationChangedEventHandler and MyClass, add the following code to the plugin dependencies registration code:

builder.Register<MyClass>().AsSelf().As<IConfigurationChangedEventHandler>().SingleInstance();

Transient Components

Transient components are supposed to be short-lived. As such, they do not need to register to the settings’ change, we can suppose the settings obtained at the component creation will stay valid during the (very short) lifetime of the component.:

public ProfilesController(IConfiguration config)
{
    _season = ((string)config.Settings.season) ?? "default";
}

Any component registered in the IoC as InstancePerDependency (the default setting) must use configuration the way.