转换器配置
自定义转换器后,通过配置即可由 ConvertManager
类调用使用。我们将以接下来的两个示例进行说明。
首先,我来定义一个加密数据 CodedData
类的转换器。如下所示:
public class CodedDataConverter : Fireasy.Data.Converter.CodedDataConverter
{
const string KEY = "1_2dg4Ib428*937#";
protected override CodedData DecodeDataFromBytes(byte[] data)
{
if (data.Length == 0)
{
return null;
}
var des = CryptographyFactory.Create(CryptoAlgorithm.DES) as SymmetricCrypto;
des.SetKey(KEY);
return new CodedData(des.Decrypt(data));
}
protected override byte[] EncodeDataToBytes(CodedData data)
{
var des = CryptographyFactory.Create(CryptoAlgorithm.DES) as SymmetricCrypto;
des.SetKey(KEY);
return des.Encrypt(data.Data);
}
}
接下来,在配置文件里增加该转换器的配置。如下所示:
- .Net Framework 下的 app.config 或 web.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="fireasy">
<section name="dataConverters" type="Fireasy.Data.Converter.Configuration.ConverterConfigurationSectionHandler, Fireasy.Data" />
</sectionGroup>
</configSections>
<fireasy>
<dataConverters>
<converter
sourceType="Fireasy.Data.CodedData, Fireasy.Data"
converterType="demo.CodedDataConverter, demo" />
</dataConverters>
</fireasy>
</configuration>
- .Net Core 下的 appsettings.json 文件
{
"fireasy": {
"dataConverters": {
"settings": [
{
"sourceType": "Fireasy.Data.CodedData, Fireasy.Data",
"converterType": "demo.CodedDataConverter, demo"
}
]
}
}
}
sourceType 表示转换的数据类型。converterType 表示转换器的类型。
如果是继承自 ValueConverterBase<T>
类,则配置会相对要简单得多。比如现在定义一个 SourceData
类的转换器。 SourceData
类是表示来源数据,是一个字典,它使用 json
格式的字符串存储。如下所示:
public class SourceData
{
public Dictionary<int, List<int>> Data { get; set; }
}
public class SourceDataConverter : ValueConverterBase<SourceData>
{
public override SourceData ConvertFrom(object value, DbType dbType = DbType.String)
{
if (value == null || value.ToString() == "null")
{
return new SourceData();
}
var data = new JsonSerializer().Deserialize<Dictionary<int, List<int>>>(value.ToString());
return new SourceData { Data = data };
}
public override object ConvertTo(SourceData value, DbType dbType = DbType.String)
{
var json = new JsonSerializer().Serialize(value.Data);
return json;
}
}
那么配置文件里可以省略 sourceType 的指定。如下所示:
- .Net Framework 下的 app.config 或 web.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="fireasy">
<section name="dataConverters" type="Fireasy.Data.Converter.Configuration.ConverterConfigurationSectionHandler, Fireasy.Data" />
</sectionGroup>
</configSections>
<fireasy>
<dataConverters>
<converter
converterType="demo.SourceDataConverter, demo" />
</dataConverters>
</fireasy>
</configuration>
- .Net Core 下的 appsettings.json 文件
{
"fireasy": {
"dataConverters": {
"settings": [
{
"converterType": "demo.SourceDataConverter, demo"
}
]
}
}
}