An exception was thrown while activating xxx->AutoMapper.Mapper->λ:AutoMapper.IConfigurationProvider

1、排除问题出现原因

1)检查Service.csproj文件
<ItemGroup>
  <Folder Include="AutoMapper\Profile\" />
</ItemGroup>

<ItemGroup>
  <PackageReference Include="AutoMapper" Version="10.1.1" />
</ItemGroup>

Profile路径已关联,AutoMapper库已安装

2)检查API的启动文件 Startup.cs
public class Startup
{
    private IServiceCollection _services;
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }
    //autofac 新增
    public ILifetimeScope AutofacContainer { get; private set; }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {

        #region AutoMapper
        List<Assembly> myAssembly = new List<Assembly>();
        myAssembly.Add(Assembly.Load($"xxx.xxx.Service"));            
        services.AddAutoMapper(myAssembly);
        services.AddScoped<IMapper, Mapper>();
        #endregion

        _services = services;
    }

    /// <summary>
    /// 将内容直接注册到AutofacContainerBuilder中
    /// </summary>
    /// <param name="builder"></param>
    public void ConfigureContainer(ContainerBuilder builder)
    {
        builder.RegisterRabbitMqBus();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //autofac 新增 可选
        this.AutofacContainer = app.ApplicationServices.GetAutofacRoot();
        IoCContainer.InitContainer(this.AutofacContainer);
    }
}

mapper相关已配置

3)检查Profile文件
public class TestMapperProfile: global::AutoMapper.Profile
{
    protected TestMapperProfile()
    {
        CreateMap <People, PeopleDTO>();
    }
}

原因找到, Profile的构造函数的访问类型为protected导致配置文件访问不到

2、解决方案

Profile的构造函数的访问类型改成public即解决问题,正确代码如下:

public class TestMapperProfile: global::AutoMapper.Profile
{
    public TestMapperProfile() // 这里改成public!
    {
        CreateMap <People, PeopleDTO>();
    }
}

疏忽大意检查了好一会,做此纪录。

若本文有帮助到阅读本文的同学,欢迎点赞、关注、收藏,互相学习交流。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GoodTimeGGB

鼓励一下!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值