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

2024-03-05 16:18:59 浏览数 (2)

1、排除问题出现原因

1)检查Service.csproj文件
代码语言:javascript复制
<ItemGroup>
  <Folder Include="AutoMapperProfile" />
</ItemGroup>

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

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

2)检查API的启动文件 Startup.cs
代码语言:javascript复制
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文件
代码语言:javascript复制
public class TestMapperProfile: global::AutoMapper.Profile
{
    protected TestMapperProfile()
    {
        CreateMap <People, PeopleDTO>();
    }
}

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

2、解决方案

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

代码语言:javascript复制
public class TestMapperProfile: global::AutoMapper.Profile
{
    public TestMapperProfile() // 这里改成public!
    {
        CreateMap <People, PeopleDTO>();
    }
}

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

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

0 人点赞