2

起動時にいくつかのクラスを再構築するためのカスタム構成を持つ .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などを使用しています。

4

1 に答える 1

2
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);
于 2011-07-21T14:32:26.490 に答える