ASP.NET Core 6 Web API升级AutoMapper后程序集加载失败求助
问题:AutoMapper升级后出现程序集加载失败错误
操作过程
- 原项目使用的NuGet包:
AutoMapper ver-12.0.1 AutoMapper.Extensions.Microsoft.DependencyInjection ver-12.0.1 - 移除了以下包:
AutoMapper.Extensions.Microsoft.DependencyInjection ver-12.0.1 - 将AutoMapper升级至:
AutoMapper ver-13.0.1
错误信息
未处理的异常。System.IO.FileNotFoundException: 未能加载文件或程序集“AutoMapper, Version=13.0.0.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005”。系统找不到指定的文件。
文件名:“AutoMapper, Version=13.0.0.0, Culture=neutral, PublicKeyToken=be96cd2c38ef1005”
在 AutoMapperServiceExtension.ConfigureAutoMappers(IServiceCollection services)
在 Program.$(String[] args) 位置 C:\Program.cs:第32行
错误指向代码:
builder.Services.ConfigureAutoMappers()
相关代码
扩展类
public static class AutoMapperServiceExtension { public static void ConfigureAutoMappers(this IServiceCollection services) { services.AddAutoMapper(typeof(BankMapperProfile)); } }
实体映射类
public class BankMapperProfile : Profile { public BankMapperProfile() { // ... } }
Program.cs
using API.Extensions; var builder = WebApplication.CreateBuilder(args); ConfigurationManager configuration = builder.Configuration; var environment = builder.Environment; // 向容器添加服务 builder.Services.AddHttpContextAccessor(); builder.Services.AddMvc(); builder.Services.AddControllers().AddNewtonsoftJson(op => op.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); builder.Services.AddControllers() .AddFluentValidation(options => { options.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly()); }); builder.Services.AddControllers(); // 配置Swagger/OpenAPI builder.Services.AddEndpointsApiExplorer(); // 配置AutoMapper builder.Services.ConfigureAutoMappers();
解决方案
1. 重新安装匹配版本的扩展包
AddAutoMapper方法属于AutoMapper.Extensions.Microsoft.DependencyInjection包,你移除该包后无法找到此方法,进而引发程序集加载异常。需安装与AutoMapper 13.0.1匹配的扩展包:
Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 13.0.1
2. 清理重建项目
- 右键项目选择「清理」
- 删除项目目录下的
bin和obj文件夹 - 右键项目选择「生成」
- 重启Visual Studio(可选,清除缓存)
3. 添加程序集绑定重定向(若仍有版本冲突)
在项目的web.config(若存在)中添加绑定重定向,强制使用13.0.1版本:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="AutoMapper" publicKeyToken="be96cd2c38ef1005" culture="neutral" /> <bindingRedirect oldVersion="0.0.0.0-13.0.1.0" newVersion="13.0.1.0" /> </dependentAssembly> </assemblyBinding> </runtime>
4. 检查依赖项一致性
打开NuGet包管理器,确认AutoMapper和其扩展包版本完全一致,无旧版本残留引用。
内容的提问来源于stack exchange,提问作者Gbenga
相关产品推荐
相关产品推荐

