AutoMapper 4.2.1






4.73/5 (9投票s)
迁移到 AutoMapper 4.2.1
引言
在 AutoMapper
4.2.1 中,大部分静态 API 已被移除,并暴露了新的基于实例的 API。升级现有项目或使用最新 AutoMapper
版本开发新项目将需要不同的方法。
在本技巧中,我们将把最新版本的 AutoMapper
集成到 MVC 项目中。
Using the Code
通过 NuGet 包管理器安装 AutoMapper
。
同时安装 Autofac
,以演示通过依赖注入传递 mapper 对象。
第一步是创建一个继承自 AutoMapper.Profile
类的类。然后,重写 Configure
函数以创建不同类之间的映射。可以有多个 Profile
类来分组相关的映射。
public class MappingProfile : Profile
{
protected override void Configure()
{
CreateMap<UserModel, UserViewModel>()
.ForMember(x => x.UserName, opt => opt.MapFrom
(y => y.FirstName + " " + y.MiddleName + " " + y.LastName))
.ForMember(x => x.UserAddress,
opt => opt.MapFrom(y => y.AddressLine1 + " " + y.AddressLine2 + " " + y.PinCode));
}
}
下一步是创建一个 Configuration
类,将 profile 类传递给 MapperConfiguration
构造函数。MapperConfiguration
对象用于使用 CreateMapper()
函数生成 mapper 对象。
public class AutoMapperConfig
{
public static IMapper Mapper;
public static void ConfigureAutoMapper()
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new MappingProfile());
});
Mapper = config.CreateMapper();
config.AssertConfigurationIsValid();
}
}
应该在应用程序启动时执行此 Configuration
。因此,需要将以下代码添加到 global.asax.cs 文件中的 Application_Start()
方法。
AutoMapperConfig.ConfigureAutoMapper();
依赖注入
由于大部分 AutoMapper
API 不是静态的,因此现在可以通过 依赖注入
传递 mapper 对象。我在这里使用 autofac 来演示如何通过 DI
传递 mapper 对象。
在类中创建一个本地 IMapper
变量,构造函数将其值分配给依赖注入的 IMapper
对象。
public class DBController : Controller
{
private readonly IDbLogger _logger;
private readonly IMapper _mapper;
public DBController(IDbLogger logger, IMapper mapper)
{
this._logger = logger;
this._mapper = mapper;
}
}
可以这样将 mapper 对象添加到 Autofac
容器中。
builder.RegisterInstance(AutoMapperConfig.Mapper)
.As<IMapper>()
.SingleInstance();
关注点
现在,可以根据功能、层等拥有一个子集 AutoMapper
映射,并且只在需要时注入一个子集。