Strongly typed app settings with Castle DictionaryAdapter

A while ago (almost 4 years ago, to be precise) Ben Hall wrote a blogpost about using Castle DictionaryAdapter to build a simple, strongly typed wrapper aroud application settings.

While extremely simple, and gets the job done, there are a few ways it can be improved. With that, this blogpost can be treated as an introduction to Castle DictionaryAdapter (which sadly has precisely zero documentation).

While the apprpach is really simple, we’re going to take a detailed look and take it slowly, which is why this post is fairly long. Buckle up.

What is DictionaryAdapter

In a nutshell DictionaryAdapter is a simple tool to provide strongly typed wrappers around IDictionary<string , object>

Here’s a simple example:

// we have a dictionary...
var dictionary = new Dictionary<string, object>
{
	{ "Name", "Stefan" },
	{ "Age", 30 }
};

// ...and an adapter factory
factory = new DictionaryAdapterFactory();

// we build the adapter for the dictionary
var adapter = factory.GetAdapter<IPerson>(dictionary);

Debug.Assert(adapter.Name == "Stefan");

Wrapping app settings

While the project is called DictionaryAdapter in fact it can do a bit more than just wrap dictionaries (as in IDictionary). It can be used to wrap XmlNodes or NameValueCollections like Configuration.AppSettings and this last scenario, is what we’re going to concentrate on.

The goals

We’ve got a few goals in mind for that project:

  • strongly typed – we don’t want our settings to be all just strings
  • grouped – settings that go together, should come together (think username and password should be part of a single object)
  • partitioned – settings that are separate should be separate (think SQL database connection string and Azure service bus url)
  • fail fast – when a required setting is missing we want to know ASAP, not much later, deep in the codebase when we first try to use it
  • simple to use – we want the junior developer who joins the team next week to be able to use it properly.

With that in mind, let’s get to it.

Getting started

DictionaryAdapter lives in Castle.Core (just like DynamicProxy), so to get started we need to get the package from Nuget:

Install-Package Castle.Core

Once this is done and you’re not using Resharper make sure to add using Castle.Components.DictionaryAdapter; to make the right types available.

The config file

Here’s our config file, we’ll be dealing with. Notice it follows a simple naming convention with prefixes to make it easy to group common settings together. This is based on a real project.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="environment-type" value="Local" />
    <add key="environment-log-minimum-level" value="Debug" />
    <add key="auth0-client-id" value="abc123abc" />
    <add key="auth0-client-secret" value="123abc123abc" />
    <add key="auth0-domain" value="abc123.auth0.com" />
    <add key="auth0-database-connection-name" value="ABC123" />
    <add key="auth0-token-expiration-seconds" value="3600" />
  </appSettings>
</configuration>

As you can see we have two sets of settings here. One for general environment configuration, and another one for integration with Auth0.

Config interfaces

Now let’s proceed to creating our interfaces, exposing the configuration values to our application. We follow a naming convention where the name of config value corresponds to type/property on the interface. This makes it trivial to see which config value maps to which property on which interface.

For clarity I’d also recommend putting the interfaces in a designated namespace, like MyApp.Configuration.

public interface IEnvironment
{
    EnvironmentType Type { get; }
    LogEventLevel LogMinimumLevel { get; }
}

public interface IAuth0
{
    string ClientId { get; }
    string ClientSecret { get; }
    string Domain { get; }
    string DatabaseConnectionName { get; }
    int TokenExpirationSeconds { get; }
}

Having the interfaces and the config we can start writing the code to put the two together

Bare minimum

Let’s rewrite the code from the beginning of the post to use our config file and interfaces. If you’re not using Resharper you’ll have to manually add a reference to System.Configuration.dll for the following to work.

var factory = new DictionaryAdapterFactory();

var environment = factory.GetAdapter<IEnvironment>(ConfigurationManager.AppSettings);

Debug.Assert(environment.Type == EnvironmentType.Local);

If we run it now, we’ll get a failure. DictionaryAdapter doesn’t know about our naming convention, so we have to teach it how to map the type/property to a config value.

Implementing DictionaryBehaviorAttribute

There are two ways to customise how DictionaryAdapter operates.

  • Transparent, using an overload to GetAdapter and passing a PropertyDescriptor with customisations there.
  • Declarative, using attributes on the adapter interfaces to specify the desired behaviour. If you’ve used Action Filters in ASP.NET MVC, it will feel familiar.

In this example we’re going to use the latter. To begin, we need to create a new attribute, inheriting from DictionaryBehaviorAttribute, and apply it to our two interfaces

public class AppSettingWrapperAttribute : DictionaryBehaviorAttribute, IDictionaryKeyBuilder
{
    private readonly Regex converter = new Regex("([A-Z])", RegexOptions.Compiled);

    public string GetKey(IDictionaryAdapter dictionaryAdapter, string key, PropertyDescriptor property)
    {
        var name = dictionaryAdapter.Meta.Type.Name.Remove(0, 1) + key;
        var adjustedKey = converter.Replace(name, "-$1").Trim('-');
        return adjustedKey;
    }
}

We create the attribute and implement IDictionaryKeyBuilder interface, which tells DictionaryAdapter we want to have a say at mapping the property to a proper key in the dictionary. Using a trivial regular expression we map NameLikeThis to Name-Like-This.

Having done that, if we run the application again, the assertion will pass.

Fail Fast

If we remove the environment-log-minimum-level setting from the config file, and run the app again, it will still pass just fine. In fact, since LogEventLevel (which comes from Serilog logging framework) in an enum, therefore a value type, if we read the property everything will seem to have worked just fine. A default value for the enum will be returned.

This is not the behaviour that we want. We want to fail fast, that is if the value is not present or not valid, we want to know. To do it, we need two modifications to our AppSettingWrapperAttribute

Eager fetching

First we want the adapter to eagerly fetch values for every property on the interface. That way if something is wrong, we’ll know, even before we try to access the property in our code.

To do that, we implement one more interface – IPropertyDescriptorInitializer. It comes with a single method, which we implement as follows:

public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors)
{
    propertyDescriptor.Fetch = true;
}

Validating missing properties

To ensure that each setting has a value, we need to insert some code into the process of reading the values from the dictionary. To do that, there is another interface we need to implement: IDictionaryPropertyGetter. This will allow us to inspect the value that has been read, and throw a helpful exception if there is no value.

public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue, PropertyDescriptor property, bool ifExists)
{
    if (storedValue != null) return storedValue;
    throw new InvalidOperationException(string.Format("App setting \"{0}\" not found!", key.ToLowerInvariant()));
}

If we run the app now, we’ll see that it fails, as we expect, telling us that we forgot to set environment-log-minimum-level in our config file.

Wrapping up

That’s it. Single attribute and a minimal amount of bootstrap code is all that’s needed to get nice, simple to use wrappers around application settings.

Additional bonus is, that this is trivial to integrate with your favourite IoC container.

All code is available in this gist.

On strongly typed application settings with Castle DictionaryAdapter

Every non-trivial .NET application ends up using configuration file for its settings. It’s the standard mechanism that’s fairly well adopted across the community. That doesn’t mean however, that it’s simple to deal with.

There have been many various approaches to dealing with the problem, including some from Microsoft. There are a few open source ones, including one from my colleague, Andrew.

Yet another (not even original) approach

This brings us to Castle DictionaryAdapter. Part of the Castle project that never got much traction, partially to poor (read non-existent) documentation. Somewhat similar to DynamicProxy, DictionaryAdapter concentrates on dynamically generating strongly typed wrappers around dictionaries or XML. The idea of using it for wrapping configuration values is not new. Ben blogged about it a few years ago, and I always liked the simplicity and readability of the approach, and how little effort it required.

I started working on a project recently, that has a whole bunch of different sets of config values, which led me to adding some small improvements to the approach.

Not just one big Config God Object

One common mistake (regardless of the approach) is that all the unrelated settings end up in a single massive configuration God Object. There is nothing inherent about the DictionaryAdapter approach forcing you to go down that path. You can split your configuration logically across a few configuration interfaces

public interface SmtpConfiguration
{
    string Name { get; set; }
    int Port { get; set; }
}

public interface SomeOtherConfig
{
    //stuff
}

// and in the config file:
<appSettings>
    <add key="name" value="value" />
    <add key="port" value="25"/>
    <!--  stuff -->
</appSettings>

Taking it a bit further, we might explicitly partition the values using prefixes:

<appSettings>
    <add key="smtp:name" value="value" />
    <add key="smtp:port" value="25"/>
    <add key="stuff:something" value="bla"/>
    <!--  other stuff -->
</appSettings>

DictionaryAdapter knows how to properly resolve prefixed values using KeyPrefixAttribute.

[KeyPrefix("smtp:")]
public interface SmtpConfiguration
{
    string Name { get; set; }
    int Port { get; set; }
}

Fail fast

One other missing big, is shortening the feedback loop. We don’t want to learn we have an invalid or missing value at some later point in the application’s lifecycle when we try to read it for the first time. We want to know about it as soon as possible. Preferably, when the application starts up (and in a test).

The first problem, we could solve with FetchAttribute Which forces a property to be read when the adapter is constructed, therefore forcing exception in cases where, for example, your property is of type TimeSpan but your config value is not a valid representation of time span.

To solve the other problem we need a little bit of code. In fact, to simplify things, we can merge that with what KeyPrefixAttribute and FetchAttribute provide, to have all the functionality we need in a single type.

public class AppSettingsAttribute : KeyPrefixAttribute, IDictionaryPropertyGetter, IPropertyDescriptorInitializer
{
    public AppSettingsAttribute(string keyPrefix) : base(keyPrefix)
    {
    }

    public object GetPropertyValue(IDictionaryAdapter dictionaryAdapter, string key, object storedValue,
        PropertyDescriptor property, bool ifExists)
    {
        if (storedValue == null && IsRequired(ifExists))
        {
            throw new ArgumentException("No valid value for '" + key + "' found");
        }
        return storedValue;
    }

    public void Initialize(PropertyDescriptor propertyDescriptor, object[] behaviors)
    {
        propertyDescriptor.Fetch = true;
    }

    private static bool IsRequired(bool ifExists)
    {
        return ifExists == false;
    }
}

Now our configuration interface changes to:

[AppSettings("smtp:")]
public interface SmtpConfiguration
{
    string Name { get; set; }
    int Port { get; set; }
}

Not only do we get a nice, readable, testable strongly typed access to our settings, that can easily be put in an IoC container. We also are going to get an early exception if we put an invalid value in the config, or we forget about doing it at all.

The full code is on github.

On Castle Windsor and open generic component arity

In the previous post I said there’s one more new feature in Windsor 3.2 related to open generic components.

Take the following class for example:

public class Foo<T, T2> : IFoo<T>
{
}

Notice it has arity of 2 (two generic parameters, T and T2) and the interface it implements has arity of 1.
If we have a generic component for this class what should be supplied for T2 when we want to use it as IFoo<Bar>?

By default, if we just register the component and then try to use it we’ll be greeted with an exception like the following:

Requested type GenericsAndWindsor.IFoo`1[GenericsAndWindsor.Bar] has 1 generic parameter(s), whereas component implementation type GenericsAndWindsor.Foo`2[T,T2] requires 2.
This means that Windsor does not have enough information to properly create that component for you.
You can instruct Windsor which types it should use to close this generic component by supplying an implementation of IGenericImplementationMatchingStrategy.
Please consut the documentation for examples of how to do that.

Specifying implementation generic arguments: IGenericImplementationMatchingStrategy

The IGenericImplementationMatchingStrategy interface allows you to plug in your own logic telling Windsor how to close the implementation type for a given requested service. The following trivial implementation simply uses string for the other argument, therefore allowing the component to be successfully constructed.

public class UseStringGenericStrategy : IGenericImplementationMatchingStrategy
{
	public Type[] GetGenericArguments(ComponentModel model, CreationContext context)
	{
		return new[]
		{
			context.RequestedType.GetGenericArguments().Single(),
			typeof (string)
		};
	}
}

The contract is quite simple, given a ComponentModel and CreationContext (which will tell you what the requested closed type is) you return the right types to use for generic arguments when closing the implementation type of the model.

You hook it up in exactly the same way as IGenericServiceStrategy (and yes, there’s an overload that allows you to specify both).

container.Register(Component.For(typeof (IFoo<>))
	.ImplementedBy(typeof (Foo<,>), new UseStringGenericStrategy())
	.LifestyleTransient());

Now the service will resolve successfully.
Generic component resolved

On Castle Windsor and open generic components

While Windsor supported open generics components since pretty much forever, there’s been some improvements in version 3.2 that I haven’t blogged about yet, but which can be pretty useful in some advanced scenarios. I’ll cover them in this and future blogpost.

Just so we’re clear – what are open generic components?

So what are open generic components? Components based on a generic type where we don’t specify the generic arguments. Like the following:

// register
container.Register(Component.For(typeof (IFoo<>))
	.ImplementedBy(typeof (Foo<>))
	.LifestyleTransient());

// will provide IFoo<Bar>, IFoo<Baz>, IFoo<any_valid_type>

In this case we say that the component provides IFoo<> closed over Bar, Baz etc

Being picky about what we’re closing over: IGenericServiceStrategy

Sometimes we want to restrict the types we want our components to support. C# language allows us to use generic constraints to specify that, and Windsor will obviously respect that, but sometimes we need to go beyond what language provides.

One realistic example might be restricting to specific types from a given assembly, like in this StackOverflow question.

Windsor 3.2 has a new hook point for just that – IGenericServiceStrategy, which allows you to plug custom logic to specify whether you want a component to support a given closed version of it’s open generic service.

Here’s a sample implementation limiting to types from a single assembly:

public class OnlyFromAssemblyStrategy : IGenericServiceStrategy
{
	private readonly Assembly assembly;

	public OnlyFromAssemblyStrategy(Assembly assembly)
	{
		this.assembly = assembly;
	}

	public bool Supports(Type service, ComponentModel component)
	{
		return service.GetGenericArguments().Single().Assembly == assembly;
	}
}

To hook the strategy:

container.Register(Component.For(typeof (IFoo<>))
	.ImplementedBy(typeof (Foo<>), new OnlyFromAssemblyStrategy(someAsembly))
	.LifestyleTransient());

Now when you need IFoo<SomeTypeFromWrongAssembly> either another component will need to supply it, or the dependency will not be satisfied (which, if the dependency is not optional, will result in exception).
Component Not Found exception

On Windsor 3.2 release

Windsor 3.2 release is now live on nuget and sourceforge.

This release is mostly about bugfixes and incremental improvements and while some breaking changes were made, for vast majority of users this will be a drop-in update.

The highlights of the release are in the documentation, so I won’t repeat them here.

End of an era

It is the last release to support .NET 3.5 and Silverlight.

Also, I’m thinking of sunsetting (such a nice word) Remoting facility, Factory Support facility (the one that allows you to specify factory method via XML, not to be confused with Typed Factory facility), Event Wiring facility and Synchronize facility.

Obviously, Windsor being a community driven project, if someone wants to step in and take over any of these facilities we’ll keep updating them. Otherwise this will likely be their last release.

IoC concepts: Service

As part of preparing for release of Windsor 3.1 I decided to revisit parts of Windsor’s documentation and try to make it more approachable to some completely new to IoC. This and few following posts are excerpts from that new documentation. As such I would appreciate any feedback, especially around how clearly the concepts in question are explained for someone who had no prior exposure to them.

As every technology, Windsor has certain basic concepts that you need to understand in order to be able to properly use it. Fear not – they may have scary and complicated names and abstract definitions but they are quite simple to grasp.

Service

First concept that you’ll see over and over in the documentation and in Windsor’s API is service. Actual definition goes somewhat like this: “service is an abstract contract describing some cohesive unit of functionality”.

Service in Windsor and WCF service
The term service is extremely overloaded and has become even more so in recent years. Services as used in this documentation are a broader term than for example WCF services.

Now in plain language, let’s imagine you enter a coffee shop you’ve never been to. You talk to the barista, order your coffee, pay, wait and enjoy your cup of perfect Cappuccino. Now, let’s look at the interactions you went through:

  • specify the coffee you want
  • pay
  • get the coffee

They are the same for pretty much every coffee shop on the planet. They are the coffee shop service. Does it start making a bit more sense now? The coffee shop has clearly defined, cohesive functionality it exposes – it makes coffee. The contract is pretty abstract and high level. It doesn’t concern itself with “implementation details”; what sort of coffee-machine and beans does the coffee shop have, how big it is, and what’s the name of the barista, and color of her shirt. You, as a user don’t care about those things, you only care about getting your cappuccino, so all the things that don’t directly impact you getting your coffee do not belong as part of the service.

Hopefully you’re getting a better picture of what it’s all about, and what makes a good service. Now back in .NET land we might define a coffee shop as an interface (since interfaces are by definition abstract and have no implementation details you’ll often find that your services will be defined as interfaces).

public interface ICoffeeShop
{
   Coffee GetCoffee(CoffeeRequest request);
}

The actual details obviously can vary, but it has all the important aspects. The service defined by our ICoffeeShop is high level. It defines all the aspects required to successfully order a coffee, and yet it doesn’t leak any details on who, how or where prepares the coffee.

If coffee is not your thing, you can find examples of good contracts in many areas of your codebase. IController in ASP.NET MVC, which defines all the details required by ASP.NET MVC framework to successfully plug your controller into its processing pipeline, yet gives you all the flexibility you need to implement the controller, whether you’re building a social networking site, or e-commerce application.

If that’s all clear and simple now, let’s move to the next important concept (in the next post).

Windsor’s Nuget package and code – your input needed

As we’re nearing to release the next version of Castle Windsor I’m also thinking about how we could leverage Nuget better.

One idea I had was to include elements I (and most people) end up writing in every project using Windsor – a Bootstrapper class which is responsible for setting up the container, a folder for installers, and an installer in it.

This is what a solution would look like after creating an empty project and installing Windsor via Nuget:

Visual Studio after installing Windsor via Nuget, including code

Visual Studio after installing Windsor via Nuget

The goal of this would be to put the code in your solution having the bare-bone useful minimum, with intention you’d customize it as needed. Most people end up adding at least and so the bootstrapper would look like this:

using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Resolvers.SpecializedResolvers;
using Castle.Windsor;
using Castle.Windsor.Installer;

namespace WpfApplication1
{
    public class WindsorBootstrapper
    {
        public IWindsorContainer BuildContainer()
        {
            IWindsorContainer container = Instantiate();
            Configure(container);
            InstallComponents(container);
            return container;
        }

        private IWindsorContainer Instantiate()
        {
            return new WindsorContainer();
        }

        private void Configure(IWindsorContainer container)
        {
            container.AddFacility<TypedFactoryFacility>();

            var resolver = new CollectionResolver(container.Kernel, allowEmptyCollections: false);
            container.Kernel.Resolver.AddSubResolver(resolver);
        }

        private void InstallComponents(IWindsorContainer container)
        {
            container.Install(FromAssembly.This());
        }
    }
}

The installer is a tougher nut to crack. Because they are so specific to your application it’s impossible to create a generic one that will be useful. I’m thinking either about shooting for the widest scenario, and create either an empty one, with generic name like RepositoriesInstaller, or to get it one step farther and add some real-like code, but comment it out, like this:

using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;

namespace WpfApplication1.Installers
{
    public class RepositoriesInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            // Customize to the needs of your application

            //container.Register(Classes.FromThisAssembly()
            //                       .BasedOn(typeof (IRepository<>))
            //                       .WithService.Base()
            //                       .LifestyleTransient());
        }
    }
}

My hope is, this would give advanced users a jump-start and provide a gentle introduction for people new to Windsor, and push them towards established practices when using Windsor (closer to to the pit of success).

This is just an idea, and I would like to hear your feedback. What do you think about it? Do you think it should be included at all in the Castle.Windsor package, or should we create a separate package called something like Castle.Windsor-wc (for “with code”) for this?

Castle Windsor 3.0 is released

Castle Windsor

After successful beta and RC releases final version of Castle Windsor (as well as Castle Core, and a whole set of facilities) has now been released. There are no major changes between final version and RC. The difference is some minor bug fixes, improved exception messages and some small improvements all over the place.

 

The packages are available now, on Nuget (with symbols), and via standard .zip download.

 

Last but not least – thank you to everyone who downloaded beta and release candidate and provided feedback. You guys rock.

Getting closer… Castle Windsor 3 RC 1

Few weeks later than originally expected but here it is – Castle Windsor 3.0 (along with its facilities and Castle.Core) achieved release candidate status.

There is one major new feature in this release: registration API gained ability to specify properties to ignore/require. There are some scenarios where that’s useful, for example where integrating with some 3rd party framework that forces you to inherit from a base class which exposes its dependencies as properties. Creating pass-through constructors for each inherited class can be mundane. In those cases you can simply mark those base class properties as required, in which case Windsor will not allow them to be resolved unless all base property dependencies are satisfied. PropertyFilter enum supports several other most common scenarios, and for advanced cases there’s an overload that gives you more control.

Container.Register(
    Classes.FromThisAssembly()
        .BasedOn<ICommon>()
        .Configure(c => c.Properties(PropertyFilter.RequireBase)));

To address performance hit at startup Windsor no longer enables performance counters by default. Now, you have to do it explicitly:

var container = new WindsorContainer();
var diagnostic = LifecycledComponentsReleasePolicy.GetTrackedComponentsDiagnostic(container.Kernel);
var counter = LifecycledComponentsReleasePolicy.GetTrackedComponentsPerformanceCounter(new PerformanceMetricsFactory());
container.Kernel.ReleasePolicy = new LifecycledComponentsReleasePolicy(diagnostic, counter);

Full changelog is included in the packages. Please, if possible, take the time to upgrade to this version and if you find any issues report them so that the final release is rock solid. If no major issues are found, the final release will be published in two weeks.

The binaries are available on Nuget right now, and soon on our website.

Windsor 3 beta 1 – dozen of Nuget packages and SymbolSource.org support

As promised, I released Nuget packages for beta 1 of Windsor 3. This is my first major rollout of Nuget packages, so please report any issues working with them.

Nuget and beta packages

Nuget is quickly evolving and getting more useful with each release. However one feature it’s missing right now is support for pre-release packages (this is coming in the next version).

davidebbo

This is not really a big deal, however it means there are a few things you should be aware of.

Recommended version

Since the new package is a pre-release, while I would really like for everyone to start using it immediately and report all issues they find, I quite understand that many people will rather prefer to stick to the last official version for the time being. To accommodate that the new packages are not made recommended versions, so your Nuget explorer will still point to the last stable (2.5.3) version if you search for Windsor, Castle.Core or any other pre-existing package.

nuget_explorer 

If you go to command line and install one of the packages without specifying version number, it will install the latest, that is beta 1 version.

nuget_commandline

SymbolSource.org and debugging into Windsor

Folks at SymbolSource.org added recently support for Nuget (and OpenWrap as well) and the new Castle packages take advantage of that. What it gives you, is you can now easily debug into Windsor’s code, just like .NET framework reference source (there’s a simple guide at SymbolSource on how to do it).

After you’re all set you can step into any of Castle methods in your debugger and watch the magic happen. Very cool thing, even if I say so myself.

windsor-source-debugging

 

List of packages

Here’s the full list of v3 beta 1 packages (notice those are not all Castle packages, just those that were published as v3 beta 1 rollout of Windsor):

 

I hope this will make it easier for everyone to test drive Windsor. And if you find any issues, have any suggestions or ideas, do not hesitate to bring them up, either on our google group, or issue tracker.