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?