如何在 ASP.Net Core 6 中设置 AutoMapper

Meh*_*lal 27 automapper asp.net-core .net-6.0

如何在 ASP.Net Core 6 中配置 AutoMapper

我有一个用 .Net 3.1 编写的项目,所以我们有 Startup.cs 类。

我正在将其迁移到 .net core 6

现在,当我将以下配置放入我的 .Net 6 Program.cs 中时

             builder.Services.AddAutoMapper(typeof(Startup));
Run Code Online (Sandbox Code Playgroud)

我收到错误:无法找到类型或命名空间启动

有什么建议吗?我该如何修复它或在 .net 6 中配置它

小智 43

安装包

  • dotnet 添加包 AutoMapper.Extensions.Microsoft.DependencyInjection

在程序.cs

builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
Run Code Online (Sandbox Code Playgroud)

创建MappingProfiles.cs

namespace XXX.XXX.Helpers;

public class MappingProfiles: Profile {
    public MappingProfiles() {
        CreateMap<Address, AddressDto>();
    }
}
Run Code Online (Sandbox Code Playgroud)


Tin*_*ang 27

使用这一行代替:typeof(Program).Assembly

  • 您可以删除“.Assembly”位,它会正常工作[相同](https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection/blob/986267d95da70fef4c4811b59065533137bdd304/src/AutoMapper.Extensions.Microsoft。 DependencyInjection/ServiceCollectionExtensions.cs#L46-L47)。 (9认同)

小智 18

对于那些像我一样不知道的人。

  1. 通过 NuGet 或通过以下方式安装 DI 的 AutoMapper 扩展dotnet add package AutoMapper.Extensions.Microsoft.DependencyInjection
  2. 然后在 Program.cs 文件中注册服务:(builder.Services.AddAutoMapper(typeof(<name-of-profile>));在 .NET 6 中我们不再有 StartUp.cs)

我使用配置文件来进行映射配置。这是来自 Automapper 的有关配置文件的链接