我有一个带有最小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 -> Client MinimalApis.Models.ClientModel -> MinimalApis.Data.Entities.Client at lambda_method92(闭包、对象、客户端、ResolutionContext )
如何在主项目中使用概要文件?完整的源代码在GitHub上。
发布于 2022-01-21 15:09:18
可以使用以下代码使用特定的配置文件类实例化AutoMapper:
var configuration = new MapperConfiguration(cfg => cfg.AddProfile(ClientMappingProfile));
var mapper = new Mapper(configuration);若要使用依赖项注入完成此操作,请执行以下操作:
services.AddAutoMapper(config =>
{
config.AddProfile(ClientMappingProfile);
});https://stackoverflow.com/questions/70802713
复制相似问题