1

私は起動時にいくつかのクラスを再構築するためのカスタム設定を持つ.NETアプリケーションを持っています。これは、シンプル(デ)シリアライゼーションではなく、より複雑で混在しています。構成要素をアプリケーションオブジェクトにどのようにマッピングすればいいですか?

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; } 
} 

の構成要素のいくつかは、プロパティでアプリケーションオブジェクトを繰り返しますが、私は、この目的のために軽量のオブジェクトを作成し、自分のアプリケーション内の要素を使用する必要はありません。おそらく私は彼らをPOCOと呼ぶことができます。

現在、私は次があります:設定:

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

コード:

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

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

それを行うには良い方法?おそらくIoCなどを使用しています。

答えて

1
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);