msp*_*iuk 8 c# automapper asp.net-core-2.0
我正在使用:
似乎我的配置文件没有被加载,每次我调用mapper.map我得到AutoMapper.AutoMapperMappingException:'缺少类型映射配置或不支持的映射.
这是我的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();
.
.
}
Run Code Online (Sandbox Code Playgroud)
在另一个名为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; }
}
}
Run Code Online (Sandbox Code Playgroud)
并在服务类中以这种方式调用地图
public StatusDTO GetById(int statusId)
{
var status = statusRepository.GetById(statusId);
return mapper.Map<Status, StatusDTO>(status); //map exception here
}
Run Code Online (Sandbox Code Playgroud)
调用statusRepository.GetById后,status具有值
对于我的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();
}
Run Code Online (Sandbox Code Playgroud)
我的猜测是我的映射没有被初始化.我该怎么检查?我错过了什么吗?我看到了AddAutoMapper()方法的重载
services.AddAutoMapper(params Assembly[] assemblies)
Run Code Online (Sandbox Code Playgroud)
我应该通过xxxMappings项目中的所有程序集.我怎样才能做到这一点?
msp*_*iuk 10
我明白了.由于我的映射属于不同的项目,我做了两件事
在ConfigureServices中,我使用了获取程序集的重载AddAutoMapper:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//register automapper
services.AddAutoMapper(Assembly.GetAssembly(typeof(StatusMappingProfile))); //If you have other mapping profiles defined, that profiles will be loaded too.
Run Code Online (Sandbox Code Playgroud)当我们在解决方案中的不同项目中映射配置文件时,解决该问题的另一个解决方案是:
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3328 次 |
| 最近记录: |