配置与扩展
1、配置文件
通过文件可以配置多个对象映射器,通过更换 default 的值即可实现无缝切换。配置文件如下:
- .Net Framework 下的 app.config 或 web.config 文件
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="fireasy">
<section name="objMappers" type="Fireasy.Common.Mapper.Configuration.ObjectMapperConfigurationSectionHandler, Fireasy.Common" />
</sectionGroup>
</configSections>
<fireasy>
<objMappers default="automapper">
<mapper name="automapper" type="Fireasy.AutoMapper.ObjectMapper, Fireasy.AutoMapper" />
<mapper name="demo" type="demo.ObjectMapper, demo" />
</objMappers>
</fireasy>
</configuration>
- .Net Core 下的 appsettings.json 文件
{
"fireasy": {
"objMappers": {
"default": "automapper",
"settings": {
"automapper": {
"type": "Fireasy.AutoMapper.ObjectMapper, Fireasy.AutoMapper"
},
"demo": {
"type": "demo.ObjectMapper, demo"
}
}
}
}
}
ObjectMapperFactory
工厂类可以根据配置创建一个 IObjectMapper
实例。如下所示:
[TestMethod]
public void TestCreateMapper()
{
var mapper1 = ObjectMapperFactory.CreateMapper();
Assert.IsNotNull(mapper1); // AutoMapper
var mapper2 = ObjectMapperFactory.CreateMapper("demo");
Assert.IsNotNull(mapper2); // demo
}
在使用 IOC
的环境中,通过构造注入或属性注入得到的 IObjectMapper
的实例对应的是指向 default 的配置项。