Spring.Net -- 如何使用用户自定义类型转换器 (Custom Type Converter )

时间:2022-08-16 09:43:01

有时我们需要在Spring.net创建对象时,自动将spring.xml配置中string类型转换为指定类型。

例如:

我们有如下两个个自定义类,其中ExoticType类在DependsOnExoticType类中被作为属性使用

public class ExoticType
{
    private string name;
       
    public ExoticType(string name)

{ this.name = name;
    }

    public string Name
    {
        get { return this.name; }
    }
}

 

 

public class DependsOnExoticType
{
    public DependsOnExoticType() {}
   
    private ExoticType exoticType;
       
    public ExoticType ExoticType
    {
        get { return this.exoticType; }
        set { this.exoticType = value; }
    }
   
    public override string ToString()
    {
        return exoticType.Name;
    }
}

 

在Spring.net配置中初始化时希望用string值赋给ExoticType类型属性,这时需要一个TypeConverter在后台进行类型转换。

<object name="sample" type="SimpleApp.DependsOnExoticType, SimpleApp">
  <property name="exoticType" value="aNameForExoticType"/>
</object>

 

我们需要自定义个TypeConverter如下:

public class ExoticTypeConverter : TypeConverter
{
public ExoticTypeConverter()
{
}

public override bool CanConvertFrom (
ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof (string))
{
return true;
}
return base.CanConvertFrom (context, sourceType);
}

public override object ConvertFrom (
ITypeDescriptorContext context,
CultureInfo culture, object value)
{
string s = value as string;
if (s != null)
{         
return new ExoticType(s.ToUpper());
}
return base.ConvertFrom (context, culture, value);
}
}

 

最后,我们需要在spring.xml配置中使用CustomeConverterConfigurer注册自定义的TypeConverter<object id="customConverterConfigurer"
type="Spring.Objects.Factory.Config.CustomConverterConfigurer, Spring.Core">
  <property name="CustomConverters">
    <dictionary>
      <entry key="SimpleApp.ExoticType">
        <object type="SimpleApp.ExoticTypeConverter"/>
      </entry>
    </dictionary>
  </property>
</object>