You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Maui中注册/解析AutoMapper.IMapper时遇无效泛型参数异常

.NET Maui中AutoMapper注册与解析异常的解决方案

异常情况说明

  • 原生DI注册时抛出:System.ArgumentException: 'Invalid generic arguments'
  • Autofac注册后解析抛出:Exception Has Been Thrown by the target of an invocation

核心排查点

  • 检查所有Profile类中的映射配置,确保CreateMap<Source, Destination>()的泛型参数类型合法,不存在未定义类型、抽象类无法实例化等问题。
  • 确认AutoMapper版本与.NET Maui版本兼容,推荐使用最新稳定版AutoMapper。
  • 若Profile中依赖了其他注入服务(如自定义类型转换器),必须在创建IMapper时传入服务提供者,保证依赖能被正确解析。

修复后的注册代码

原生DI注册方式

// 注册MapperConfiguration为单例
builder.Services.AddSingleton<MapperConfiguration>(sp =>
    new MapperConfiguration(cfg =>
    {
        cfg.AddProfile<ModelProfile>();
        cfg.AddProfile<DtoProfile>();
        cfg.AddProfile<ItmProfile>();
    }));

// 通过服务提供者创建IMapper实例并注册
builder.Services.AddSingleton<IMapper>(sp =>
    sp.GetRequiredService<MapperConfiguration>().CreateMapper(sp.GetService));

Autofac注册方式

// 注册MapperConfiguration为单例
container.Register(cfc => new MapperConfiguration(cfg => 
    {
        cfg.AddProfile<ModelProfile>();
        cfg.AddProfile<DtoProfile>();
        cfg.AddProfile<ItmProfile>();
    }))
    .SingleInstance();

// 传入Autofac服务解析器创建IMapper并注册
container.Register(ctx => 
    ctx.Resolve<MapperConfiguration>().CreateMapper(ctx.Resolve))
    .As<IMapper>()
    .SingleInstance();

内容的提问来源于stack exchange,提问作者Nambukarthy Raveendran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 20:35:08