Overriding app.config settings

Component: NServiceBus
NuGet Package NServiceBus (5.x)
Standard support for version 5.x of NServiceBus has expired. For more information see our Support Policy.

NServiceBus uses the running process config file as its default source of configuration. NServiceBus allows changing the default behavior and customizing the location from where the configuration is loaded. This can be done for the whole configuration or a specific sections.

IProvideConfiguration, IConfigurationSource and CustomConfigurationSource have been deprecated in Version 7. See the Version 7 upgrade guide for more information.

Overriding App.Config section

A configuration for a specific section can be overridden using the IProvideConfiguration<T> interface. For example, rather than providing the RijndaelEncryptionServiceConfig in app.config the code below provides an alternative configuration that will be used as long as RijndaelEncryptionServiceConfig is found in the types scanned:

class CustomRijndaelEncryptionServiceConfigProvider :
    IProvideConfiguration<RijndaelEncryptionServiceConfig>
{
    public RijndaelEncryptionServiceConfig GetConfiguration()
    {
        return new RijndaelEncryptionServiceConfig
        {
            Key = "gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6"
        };
    }
}

Code only configuration

If the endpoint needs to load its configuration from some other source than the 'app.config', an implementation of IConfigurationSource interface can be registered as a custom configuration source. This approach enables retrieving the configuration from any location: a database, a web service, etc..

Registering custom configuration source

This code instructs NServiceBus to use MyCustomConfigurationSource as custom configuration source:

busConfiguration.CustomConfigurationSource(new MyCustomConfigurationSource());

Provide configuration from custom location (not app.config)

GetConfiguration method provides data for RijndaelEncryptionServiceConfig directly in code, while allowing all other configuration sections to be retrieved from the config file.

public class MyCustomConfigurationSource :
    IConfigurationSource
{
    public T GetConfiguration<T>() where T : class, new()
    {
        if (typeof(T) == typeof(RijndaelEncryptionServiceConfig))
        {
            var config = new RijndaelEncryptionServiceConfig
            {
                Key = "gdDbqRpqdRbTs3mhdZh9qCaDaxJXl+e6"
            };
            return config as T;
        }
        // leaving the rest of the configuration as is:
        return ConfigurationManager.GetSection(typeof(T).Name) as T;
    }
}

Last modified