Wednesday, May 11, 2011

Strongly typed configuration library for .Net applications


The problem

During my past projects, I were always messing with hard-coded strings when doing application configuration.  
Became more mature in writing maintainable code, I have moved these hard-coded strings to separate constant class (ex. ConstAppConfig). This have helped a bit, but the code itself were filled with custom type conversions (from app.config strings to required types) and tightly coupled with .net configuration classes. 
Later, I have got an idea to create IApplicationConfig interface, which contains all configuration properties.  
The solution with configuration interface have several benefits, over constant class: 
  • Interface contains properties with it's types 
  • Interface make easy stubbing and mocking configuration values in test code  
  • String to Type conversion are implemented in base classes, and not spread across the code  
  • Makes easy to switch between config sources. like app.config, database, test source 
  • Makes easy to do config validation at startup 
  • Base classes provides unified way to threat non-existing or null-value scenarios
  • Facilitates refactoring with automated tools 

Using the code 

Downloading library 

Up to date binaries and source code  is available at Codeplex and Nuget. 

Configuring library   

Library setup and configuration is implemented via ConfigurationServiceBuilder class.
The class has RegisterConfigInterface(param IStringConfigSource[] src) methods, which allows you to register your configuration interface, and define configuration sources. 
Configuration source is a provider of configuration strings, like System.Configuration.ConfigurationManager class. You can use predefined AppConfig source or create your own implementation. 

Using library 

After configuration were finished and method Build were called, you will be provided with instance of ConfigurationService.
This instance holds reference to implementations of all interfaces, that you have registered at configuration phase. Implementations are accessible via  For() method. 
The For() method will give you an implementation of T interface, where all property accessors will do search trough provided configuration sources.

Example code  

Configuration file  
 Collapse
xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="FooCount" value="98"/>
  </appSettings>
</configuration>  
Usage example
 Collapse
using NUnit.Framework;
using Typed.Configuration.ConfigSource;

namespace Typed.Configuration.Tests
{
    [TestFixture]
    public class ConfigServiceUsage
    {
        // Define interface with configuration properties
        public interface IConfigInterface
        {
            [FieldName("FooCount")]
            int? ItemsPerPage { get; }
            
            [FieldName("NotExistingField")]
            int? NotExistingField { get; }
        }

        [Test]
        public void FullUsageScenarioForStubSource()
        {
            var configurationServiceBuilder = new ConfigurationServiceBuilder();

            // Register configuration interface within service
            configurationServiceBuilder.RegisterConfigInterface(new AppSettingsSource(), new NullValueSource());

            // Create service instance and put it to your IoC container, or store in static vairable
            ConfigurationService configService = configurationServiceBuilder.Build();

            // Get configuration property value
            int? itemsPerPageCount = configService.For().ItemsPerPage;
            Assert.AreEqual(98, itemsPerPageCount);
            int? notExistingValue = configService.For().NotExistingField;
            Assert.IsNull(notExistingValue);
        }
    }
} 

Wednesday, March 9, 2011

Developer's notes on Mongo database

I like playing with new technologies and NoSQL and MongoDB is not an exception.
But, while working with Mongo, I have made few mistakes, that turned out to be painful to me.

1. Do not allow MongoDriver classes go beyond your DAL

Firstly, I neglected layered structure, planning my DAL for building fresh project on mongo. The original thought, was to create factory-class that will contain accessors for all mongo collections, of the application. Of course these collections were implemented with help of C# mongo driver (using MongoCollection class). That solution, soon stroked me in the back, since MongoCollection methods, provoke usage of hard-coded literals for complex queries.
After a while, a whole application were filled with a lot's of magic-strings with field names and mongo-specific commands.

Solution, that seems appropriate now, is usage of Repositories, for DDD's aggregation roots.
The idea is to stop "string plague" right at repository level. The rule of thumb - do not allow any Business Logic at repository, and do not allow any MongoCollection usages, on any layer, above than repository.

2. Plan yours select carefully

While working with SQL database, most of the time, complex and fast queries can be built, against any reasonable database structure.
So, typical workflow were to build lean domain model, persist it to database, in a way, your's ORM supports, and only than you can start thinking about querying data.
Only in rare cases data structure can be so in-efficient, that it will require refactoring.

Using mongo, you should always think upfront about querying data, and pre-compute a lot of things, before insertion of the document.
To make queries more efficient, we have redesigned storage structure of our data, already 3 times, in just 2 months!

3. None of yours assumptions SQL assumptions can be applied to mongo

If you'll try to bring any assumptions, about tables from SQL world to mongo, it will bite you back soon! Even most basic ones should be checked with mongo documentation.
A part of our application were build, with assumption, that no duplicated records can be returned from collection. After few "impossible" exceptions, I have realized, that sometimes records can be duplicated, if you are using cursor feature. It's not bad by itself, but thanks to my implication, that this is impossible, a lot of code should be re-tested and re-factored, to handle such cases.

4. Schema-less does't mean, that you should't care about it.

My first impression, were "Woo-hoo! No more boring alter-table scripts, just add a field, that's it". But actually, whole responsibility of management database versions is moved to your's build script or DAL code.

Tuesday, March 1, 2011

.Net IoC performance comparison

Finally, I have compared performance of most widely-used IoC containers.
I'am clearly understand, that for IoC performance, in most cases, is not an issue, but I were still curious enough to test.
Here are the results:
Name Total PerRequest
Structure Map 377ms 0.377ms
Autofac 287ms 0.287ms
Unity 351ms 0.351ms
Ninject 2638ms 2.638ms
Manual 1ms 0.001ms

Test source is available via GitHub
Assumptions, behind the test, is optimized for Web scenario, where several threads request classes in different scopes.