AutoMapper映射异常求助:跨项目Profile配置未被识别问题
解决AutoMapper跨项目Profile未加载的映射错误
问题出在你注册AutoMapper的方式上:builder.Services.AddAutoMapper(typeof(Program)) 只会扫描Program类所在项目中的所有Profile子类,而你的Profile定义在另一个项目里,自然不会被识别到,导致映射配置缺失。
给你几个直接可行的解决办法:
- 直接指定Profile所在项目的某个类型(比如你的Profile类本身)来扫描:
// 假设你的Profile类叫UserProfile,在目标类库项目里 builder.Services.AddAutoMapper(typeof(UserProfile)); - 如果有多个项目都包含Profile,可传入多个类型一次性完成扫描:
builder.Services.AddAutoMapper(typeof(UserProfile), typeof(OrderProfile)); - 也可以直接传入Profile所在项目的程序集:
// 替换成你Profile所在项目的程序集名称 builder.Services.AddAutoMapper(Assembly.Load("YourProfileProjectAssemblyName"));
另外别忘了验证两个关键点:
- 你的Profile类必须是public的,并且正确继承了
AutoMapper.Profile - 在Profile的构造函数里确实配置了正确的映射规则,比如:
public class UserProfile : Profile { public UserProfile() { CreateMap<SourceEntity, TargetDto>(); } }
内容的提问来源于stack exchange,提问作者ilumini
相关产品推荐
相关产品推荐

