首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用.NET6测试AutoMapper最小API

用.NET6测试AutoMapper最小API
EN

Stack Overflow用户
提问于 2022-01-21 14:14:42
回答 1查看 2.5K关注 0票数 1

我有一个带有最小API的.NET6项目。这是密码

代码语言:javascript
复制
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ClientContext>(opt => 
  opt.UseInMemoryDatabase("Clients"));
builder.Services
  .AddTransient<IClientRepository,
                ClientRepository>();
builder.Services
  .AddAutoMapper(Assembly.GetEntryAssembly());

var app = builder.Build();

// Get the Automapper, we can share this too
var mapper = app.Services.GetService<IMapper>();
if (mapper == null)
{
    throw new InvalidOperationException(
      "Mapper not found");
}

app.MapPost("/clients",
  async (ClientModel model,
         IClientRepository repo) =>
  {
      try
      {
          var newClient = mapper.Map<Client>(model);
          repo.Add(newClient);
          if (await repo.SaveAll())
          {
              return Results.Created(
                $"/clients/{newClient.Id}",
                mapper.Map<ClientModel>(newClient));
          }
      }
      catch (Exception ex)
      {
          logger.LogError(
            "Failed while creating client: {ex}",
            ex);
      }
      return Results.BadRequest(
        "Failed to create client");
  });

这个代码起作用了。我有一个简单的Profile用于AutoMapper

代码语言:javascript
复制
public class ClientMappingProfile : Profile
{
    public ClientMappingProfile()
    {
        CreateMap<Client, ClientModel>()
          .ForMember(c => c.Address1, o => o.MapFrom(m => m.Address.Address1))
          .ForMember(c => c.Address2, o => o.MapFrom(m => m.Address.Address2))
          .ForMember(c => c.Address3, o => o.MapFrom(m => m.Address.Address3))
          .ForMember(c => c.CityTown, o => o.MapFrom(m => m.Address.CityTown))
          .ForMember(c => c.PostalCode, o => o.MapFrom(m => m.Address.PostalCode))
          .ForMember(c => c.Country, o => o.MapFrom(m => m.Address.Country))
          .ReverseMap();
    }
}

我编写了一个NUnit测试和一个xUnit测试。在这两种情况下,当我调用API时都会收到错误。

程序:错误:在创建客户端时失败: AutoMapper.AutoMapperMappingException:缺少类型映射配置或不支持的映射。 映射类型: ClientModel -> Client MinimalApis.Models.ClientModel -> MinimalApis.Data.Entities.Client at lambda_method92(闭包、对象、客户端、ResolutionContext )

如何在主项目中使用概要文件?完整的源代码在GitHub上。

EN

回答 1

Stack Overflow用户

发布于 2022-01-21 15:09:18

可以使用以下代码使用特定的配置文件类实例化AutoMapper:

代码语言:javascript
复制
var configuration = new MapperConfiguration(cfg => cfg.AddProfile(ClientMappingProfile));
var mapper = new Mapper(configuration);

若要使用依赖项注入完成此操作,请执行以下操作:

代码语言:javascript
复制
services.AddAutoMapper(config =>
{
    config.AddProfile(ClientMappingProfile);
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70802713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档