Overriding app.config settings

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

NServiceBus uses the process config file as its default source of configuration. The extensibility of NServiceBus allow changing many of its behaviors, including where it gets its configuration. This can be done across all of NServiceBus or a specific part subset of features.

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

Overriding App.Config section

The preferred method of overriding a specific section is to use the IProvideConfiguration<T> model. For example, rather than providing the RijndaelEncryptionServiceConfig in app.config:

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

Adding the code above is enough since NServiceBus will automatically use if found in the types scanned.

Code only configuration

If the endpoint needs to derive its configuration from somewhere other than the 'app.config', write a class that implements IConfigurationSource and in it retrieve the configuration from any location: a database, a web service, anything.

Initialize the bus to use the custom configuration source

var configure = Configure.With();
// this call needs to happen right after With()
configure.CustomConfigurationSource(new MyCustomConfigurationSource());

Define the custom configuration source to provide the configuration values instead of app.config

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;
    }
}

The initialization code instructs NServiceBus to use a CustomConfigurationSource, passing in an instance of a new object: MyCustomConfigurationSource. Its GetConfiguration method provides data for RijndaelEncryptionServiceConfig directly in code, while allowing all other configuration sections to be retrieved from the config file.


Last modified