How better to map configuration elements to application objects?

887 views Asked by At

I have a .NET application which has a custom configuration to re-construct some classes on startup. That's not a plain (de)serialization, that's more complex and mixed.

class FooElement : ConfigurationElement
{
     static ConfigurationProperty propValue = new ConfigurationProperty("value", typeof(int));
     static ConfigurationProperty propType = new ConfigurationProperty("type", typeof(string));

     [ConfigurationProperty("value")]
     public int Value
     {
         get { return (int)this[propValue] }
         set { this[propValue] = value }
     }

     [ConfigurationProperty("type")]
     public string Type
     {
         get { return (int)this[propType] }
         set { this[propType] = value }
     }
}

class Foo : IFoo
{
    public int Value { get; set; 
    public string Type { get; set; }
}

Some of configuration elements repeats application objects by properties, but I don't want to use elements in my application, I created light-weight objects for this purpose. Probably I can call them POCOs.

Currently I have next: Config:

<elements>
    <add type="MyProj.Foo, MyProj" value="10" />
</elements>

Code:

elements.Select(e => (IFoo)Activator.CreateInstance(e.Type, e));

public Foo(FooElement element)
{
    this.Value = element.Value;
}

How to better to do that? Maybe using IoC or something similar.

1

There are 1 answers

0
abatishchev On BEST ANSWER
interface IConfigurationConverter<TElement, TObject>
{
    TObject Convert(TElement element);
}

class FooConfigurationConverter : IConfigurationConverter<FooElement, Foo>
{
    public Foo Convert(FooElement element)
    {
        return new Foo { Value = element.Value };
    }
}

FooConfigurationConverter converter = IoC.Resolve<IConfigurationConverter<FooElement, Foo>>();
Foo foo = converter.Convert(element);