Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable types as configuration properties

Is it possible to use immutable types as configuration properties with .NET's configuration API?

Let's say I have an immutable type called MyClass:

public class ImmutableClass
{
    private readonly int value;

    public ImmutableClass(int value)
    {
        this.value = value;
    }

    public int Value
    {
        get { return this.value; }
    }
}

I would like to use this type as a configuration property in a ConfigurationSection:

public class MyConfigurationSection : ConfigurationSection
{
    [ConfigurationProperty("foo")]
    public ImmutableClass Foo
    {
        get { return (ImmutableClass)base["foo"]; }
        set { base["foo"] = value; }
    }
}

When I do this, I can't serialize and deserialize MyConfigurationSection because it throws this exception:

System.Configuration.ConfigurationErrorsException: The value of the property 'criterion' cannot be converted to string. The error is: Unable to find a converter that supports conversion to/from string for the property 'criterion' of type 'FindCriterion'.

If I derive ImmutableClass from ConfigurationElement, I get this exception when I try to serialize and deserialize the configuration section:

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.MissingMethodException: No parameterless constructor defined for this object.

I have full control over ImmutableClass, so I can implement whichever interface is needed.

Is there any way I can hook into the configuration API so that ImmutableClass can be used in this way?

like image 470
Mark Seemann Avatar asked Sep 18 '09 11:09

Mark Seemann


1 Answers

Personally I think you would do better to separate out the data in the configuration section (which seemingly needs to be mutable), and how you represent it in your object model. There is nothing stopping you having two representations - a simple (DTO/POCO) version for config, and your custom version (immutable in this case) for real usage in your app.

like image 74
Marc Gravell Avatar answered Oct 05 '22 12:10

Marc Gravell