Startup 中是这么配置 AutoMapper 的
IConfigurationProvider config = new MapperConfiguration(cfg =>
{
//...
});
services.AddSingleton(config);
services.AddScoped<IMapper, Mapper>();
ProjectTo 是这么使用的
public class FeedService : IFeedService
{
private readonly IMapper _mapper;
public FeedService(IMapper mapper)
{
_mapper = mapper;
}
public async Task<IEnumerable<T>> GetFeedsAsync<T>(FeedQuery feedQuery)
{
return await _feedRepository.GetFeeds(feedQuery)
.ProjectTo<T>(_mapper)
.ToListAsync();
}
}
但运行时报错
Mapper not initialized. Call Initialize with appropriate configuration. If you are trying to use mapper instances through a container or otherwise, make sure you do not have any calls to the static Mapper.Map methods, and if you're using ProjectTo or UseAsDataSource extension methods, make sure you pass in the appropriate IConfigurationProvider instance.
at AutoMapper.Mapper.get_Configuration()
at AutoMapper.QueryableExtensions.Extensions.ProjectTo[TDestination](IQueryable source, Object parameters, Expression`1[] membersToExpand)
请问如何解决?
...
http://www.cnblogs.com/dudu/p/8279114.html
额,博客博问都是园主发的啊,你这个回复估计没get到园主的点吧
汗,我后来也发现自己之前解决过这个问题,但刚试了之前的解决方法,还是不行
@dudu: 所以我打了... 你的原链接在这里,希望你自己能帮到自己哈哈。https://q.cnblogs.com/q/102979/
我没用过ProjectTo,好处就是比Mapper.Map<>()少一行代码?
@找不到一个满意的昵称: 好处是让 EF Core 生成的 SQL 语句只 SELECT map 后的字段
@dudu: 涨姿势了,今天才知道AutoMapper.EF6这个东西
把 _mapper
改为 _mapper.ConfigurationProvider
的确可以,自己之前解决过的问题竟然忘了。为了避免再出现这个问题,不注入 IMapper
,直接注入 IConfigurationProvider
public class FeedService : IFeedService
{
private readonly IConfigurationProvider _mapperConfiguration;
public FeedService(IConfigurationProvider mapperConfiguration)
{
_mapperConfiguration = mapperConfiguration;
}
public async Task<IEnumerable<T>> GetFeedsAsync<T>(FeedQuery feedQuery)
{
return await _feedRepository.GetFeeds(feedQuery)
.ProjectTo<T>(_mapperConfiguration)
.ToListAsync();
}
}
另外 Statup 中的配置改为使用 AutoMapper.Extensions.Microsoft.DependencyInjection
services.AddAutoMapper(cfg =>
{
//...
});