【发布时间】:2022-01-21 14:14:42
【问题描述】:
我有一个 API 最少的 .NET6 项目。这是代码
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
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 -> 客户端 MinimalApis.Models.ClientModel -> MinimalApis.Data.Entities.Client 在 lambda_method92(Closure , Object , Client , ResolutionContext )
如何在主项目中使用配置文件?完整的源代码在GitHub。
【问题讨论】:
-
Assembly.GetEntryAssembly()-> 单元测试项目的入口程序集是什么。提示:这不是定义配置文件的项目。 -
你完全正确。从 API 的角度来看,这是可行的。我是否必须为测试项目添加另一个?
-
我通常会使用
typeof(someClassInMyAssembly).Assembly而不是Assembly.GetEntryAssembly() -
非常感谢@Llama 它正在工作!
标签: c# automapper webapi .net-6.0