29
loading...
This website collects cookies to deliver better user experience
This article is about dying technology - .NET framework web.config and app.config XML files.
.NET Core overhauled application configuration, jettisoning .config XML files in favor of app settings JSON files, and .NET 5 brings those configuration changes back into "Framework" .NET.
For those of us who are still acting as caretakers for geriatric .NET framework apps using .config files though, here's a tool to make it a bit easier...
The code in these packages was inspired by a blog post called "The Last Configuration Section Handler I'll Ever Need" by Craig Andera that I read way back in 2003 🤯. I've been using this technique since then, and finally "NuGet-ed" it a few years ago.
public class Foo
{
public string Bar { get; set; }
public decimal Baz { get; set; }
}
<configuration>
<configSections>
<section name="Foo" type="SparkyTools.XmlConfig.ConfigurationSectionDeserializer, SparkyTools.XmlConfig" />
<section name="FooList" type="SparkyTools.XmlConfig.ConfigurationSectionListDeserializer, SparkyTools.XmlConfig" />
</configSections>
<Foo type="FooNamespace.Foo, FooAssemblyName">
<Bar>bar</Bar>
<Baz>123.45</Baz>
</Foo>
<FooList type="FooNamespace.Foo, FooAssemblyName">
<Foo>
<Bar>bar1</Bar>
<Baz>111.11</Baz>
</Foo>
<Foo>
<Bar>bar2</Bar>
<Baz>222.22</Baz>
</Foo>
</FooList>
public class Foo
{
[XmlAttribute("bar")]
public string Bar { get; set; }
[XmlAttribute("baz")]
public decimal Baz { get; set; }
}
<FooList type="FooNamespace.Bar, FooAssemblyName">
<Foo bar="bar1" baz="111.11" />
<Foo bar="bar2" baz="222.22" />
</FooList>
Foo foo =
ConfigurationSectionDeserializer.Load<Foo>("Foo");
IList<Foo> fooList =
ConfigurationSectionListDeserializer.Load<Foo>("FooList");
using SparkyTools.DependencyProvider;
public class Qux
{
private readonly Foo _foo;
public Qux(IDependencyProvider<Foo> fooProvider)
{
_foo = fooProvider.GetValue();
}
}
using SparkyTools.XmlConfig;
. . .
var qux = new Qux(
ConfigurationSectionDeserializer.DependencyProvider<Foo>("Foo"));
public class Quux
{
public void DoThing()
{
if (ConfigurationManager.AppSettings["featureEnabled"] == "true")
{
// Do that thang!
}
}
}
ConfigurationManager.AppSettings["serviceUrl"] = "http://fakeurl";
public class Quux
{
private readonly Func<string, string> _getAppSetting;
public Quux(IDependencyProvider<Func<string, string> appSettingsProvider)
{
_getAppSetting = appSettingsProvider.GetValue();
}
public void DoThing()
{
if (_getAppSetting("featureEnabled") == "true")
{
// Do that thang!
}
}
}
using SparkyTools.XmlConfig;
...
var qux = new Quux(AppSettings.DependencyProvider());