Skip to content

Configuration Settings

Joel Mitchell edited this page Jan 25, 2017 · 4 revisions

Cofoundry includes a system for easily creating strongly typed configuration settings just by defining a POCO class that inherits from IConfigurationSettings. These settings classes are automatically picked up by the DI system and bound to your config source (e.g. web.config/app.config) at runtime.

Under the covers we use IConfigurationService to retrieve settings and also check the configuration is valid using IModelValidationService so you can also take advantage of data annotations such as [Required] and [MaxLength] to ensure that setting values are entered correctly.

Setting Names

In the default implementation settings are taken from the appSettings node of your config file and use the format {ClassName}:{PropertyName} where ClassName has the text "Settings" removed from the end, e.g. 'ContactForm:IsContactFormEnabled'

To add an additional level of namespacing to your settings you can implement INamespacedConfigurationSettings, which is what Cofoundry uses internally to make names like 'Cofoundry:Mail:DefaultFromAddress'. This is particularly useful if you are making a plugin and want to ensure your config settings don't conflict.

Example

web.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <add key="ContactForm:IsContactFormEnabled" value="True" />
        <add key="ContactForm:NotificationToAddress" value="[email protected]" />
    </appSettings>
</configuration>

ContactFormSettings.cs:

using Cofoundry.Core.Configuration;

public class ContactFormSettings : IConfigurationSettings
{
    public bool IsContactFormEnabled { get; set; }
    
    [Required]
    [EmailAddress]
    public string NotificationToAddress { get; set; }
}

ContactController.cs:

public class ContactController : Controller
{
    private readonly ContactFormSettings _simpleTestSiteSettings;

    public ContactController(
        ContactFormSettings simpleTestSiteSettings
        )
    {
        _simpleTestSiteSettings = simpleTestSiteSettings;
    }
    
    // .. implementation
}
Clone this wiki locally