Skip to content

Instantly share code, notes, and snippets.

@teyc
Last active April 15, 2016 02:08
Show Gist options
  • Select an option

  • Save teyc/c74fe32a0bc305977c04 to your computer and use it in GitHub Desktop.

Select an option

Save teyc/c74fe32a0bc305977c04 to your computer and use it in GitHub Desktop.
ConfigInjector - Dotted Nested Class

Introduction

ConfigInjector is nice, but how do you inject configuration names like Octopus.Deploy.Environment or webPages:Enabled ?

We solve this by registering SettingKeyConvention with ConfigurationConfigurator. I've defined two in this Gist to handle settings that contains dots as well as settings that contains arbitrary characters.

public class AttributedSettingKeyConvention : ISettingKeyConvention
{
public string KeyFor(Type settingType)
{
var attribute = (ConfigurationSettingAttribute) settingType.GetCustomAttributes(typeof(ConfigurationSettingAttribute), false).FirstOrDefault();
if (attribute != null)
{
return attribute.Key;
}
else
{
return null;
}
}
}
public class ConfigurationSettingAttribute : Attribute
{
public string Key { get; set; }
}
[ConfigurationSetting(Key="WebPages:Enabled")]
public class WebPages_Enabled
{
}
class DottedSettingKeyConvention : ISettingKeyConvention
{
public string KeyFor(Type settingType)
{
return GetDottedParentName(settingType.DeclaringType, settingType.Name);
}
private string GetDottedParentName(Type settingType, string rest = null)
{
if (settingType == null) return rest;
if (!settingType.IsNested) return $"{settingType.Name}.{rest}";
return GetDottedParentName(settingType.DeclaringType, $"{settingType.Name}.{rest}");
}
}
public class Octopus
{
public class Environment
{
// maps to "Octopus.Environment.Name"
public class Name : ConfigurationSetting<string>
{
}
}
}
ConfigurationConfigurator.RegisterConfigurationSettings()
.FromAssemblies(ThisAssembly)
.RegisterWithContainer(configSetting => builder.RegisterInstance(configSetting)
.AsSelf()
.SingleInstance())
.WithSettingKeyConventions(
new DottedSettingKeyConvention(),
new AttributedSettingKeyConvention())
.DoYourThing();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment