分层架构中Mapster跨层配置使用及Assembly选择问题解决
问题场景
在分层架构中,Web层Program.cs配置Mapster服务时,需要加载服务层的映射配置,但遇到Assembly选择导致的CS8604空引用警告,且无法正确加载服务层映射逻辑。
原Web层配置代码
var config = TypeAdapterConfig.GlobalSettings; config.Scan(Assembly.GetAssembly(typeof(UserMappingConfig))); builder.Services.AddSingleton(config); builder.Services.AddScoped<IMapper, ServiceMapper>();
服务层映射类(实现IRegister)
namespace Exams.Service.Mapping { public class QuestionMappingConfig : IRegister { public void Register(TypeAdapterConfig config) { config.NewConfig<QuestionViewModel, Question>().IgnoreNullValues(true); config.NewConfig<List<QuestionViewModel>,List<Question>>().IgnoreNullValues(true); config.NewConfig<Question, QuestionViewModel>().IgnoreNullValues(true); } } }
收到的警告
Severity Code Description Project File Line Suppression State
Warning CS8604 Possible null reference argument for parameter 'assemblies' in 'IList TypeAdapterConfig.Scan(params Assembly[] assemblies)'.
核心问题分析
Assembly.GetAssembly(typeof(T))存在返回null的风险(比如程序集未被正确加载),导致传递给Scan方法的参数触发空引用警告;同时原代码未扫描服务层程序集,无法加载服务层的映射配置。
解决步骤
1. 安全获取目标程序集
替换Assembly.GetAssembly为typeof(T).Assembly,后者会直接返回包含该类型的已加载程序集,不会返回null,从根源消除CS8604警告。
2. 扫描服务层+Web层的程序集
在Web层配置中,同时扫描服务层(包含QuestionMappingConfig的程序集)和Web层(包含UserMappingConfig的程序集)的所有IRegister实现类。
修改后的Web层Program.cs代码:
var config = TypeAdapterConfig.GlobalSettings; // 扫描服务层程序集(通过服务层映射类获取) config.Scan(typeof(Exams.Service.Mapping.QuestionMappingConfig).Assembly); // 扫描Web层程序集(通过Web层映射类获取) config.Scan(typeof(UserMappingConfig).Assembly); builder.Services.AddSingleton(config); builder.Services.AddScoped<IMapper, ServiceMapper>();
若需一次性扫描多个程序集,可合并为:
var config = TypeAdapterConfig.GlobalSettings; config.Scan( typeof(Exams.Service.Mapping.QuestionMappingConfig).Assembly, typeof(UserMappingConfig).Assembly ); builder.Services.AddSingleton(config); builder.Services.AddScoped<IMapper, ServiceMapper>();
3. 确保项目引用正确
确认Web层项目已添加对服务层项目的引用,否则服务层程序集无法被Web层加载,映射配置将不会生效。
内容的提问来源于stack exchange,提问作者Berk KARASU

