【发布时间】:2017-09-19 21:55:53
【问题描述】:
我正在使用:
- AutoMapper 6.1.1
- AutoMapper.Extensions.Microsoft.DependencyInjection 3.0.1
似乎我的配置文件没有被加载,每次我调用 mapper.map 我都会得到 AutoMapper.AutoMapperMappingException: 'Missing type map configuration or unsupported mapping.'
这里是我的 Startup.cs 类的 ConfigureServices 方法
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//register automapper
services.AddAutoMapper();
.
.
}
在另一个名为 xxxMappings 的项目中,我有我的映射配置文件。 示例类
public class StatusMappingProfile : Profile
{
public StatusMappingProfile()
{
CreateMap<Status, StatusDTO>()
.ForMember(t => t.Id, s => s.MapFrom(d => d.Id))
.ForMember(t => t.Title, s => s.MapFrom(d => d.Name))
.ForMember(t => t.Color, s => s.MapFrom(d => d.Color));
}
public override string ProfileName
{
get { return this.GetType().Name; }
}
}
并在服务类中以这种方式调用地图
public StatusDTO GetById(int statusId)
{
var status = statusRepository.GetById(statusId);
return mapper.Map<Status, StatusDTO>(status); //map exception here
}
status 在调用 statusRepository.GetById 后有值
对于我的 Profile 类,如果不是从 Profile 继承,而是从 MapperConfigurationExpression 继承,我得到了如下所示的单元测试,表明映射良好。
[Fact]
public void TestStatusMapping()
{
var mappingProfile = new StatusMappingProfile();
var config = new MapperConfiguration(mappingProfile);
var mapper = new AutoMapper.Mapper(config);
(mapper as IMapper).ConfigurationProvider.AssertConfigurationIsValid();
}
我的猜测是我的映射没有被初始化。 我该如何检查?我错过了什么吗? 我看到 AddAutoMapper() 方法的重载
services.AddAutoMapper(params Assembly[] assemblies)
我是否应该传递我的 xxxMappings 项目中的所有程序集。我该怎么做?
【问题讨论】:
标签: c# automapper asp.net-core-2.0