Reputation: 141
I have a .NET Core 3.1 API with the following Nuget packages:
I'm trying to map a value from an entity to a dto using a ValueResolver and I'm having an exception:
AutoMapperMappingException: Cannot create an instance of type TestAutomapperResolver.Mapping.CustomResolver
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAutoMapper(cfg => cfg.AddMaps(typeof(TestProfile).Assembly));
}
TestProfile.cs
public class TestProfile : Profile
{
public TestProfile()
{
CreateMap<TestEntity, TestDto>()
.ForMember(src => src.PropertyToBeMappedByResolver, opts => opts.MapFrom<CustomResolver>());
}
}
public class CustomResolver : IValueResolver<TestEntity, TestDto, string>
{
public string Resolve(TestEntity source, TestDto destination, string destMember, ResolutionContext context)
{
return "String generated with resolver";
}
}
When doing mapper.CreateMap<TestDto>(entity);
I'm receiving that exception.
By the way, using this resolver as opts => opts.MapFrom(CustomResolver())
is not an option because I want to inject some service into that resolver.
Any idea?
Upvotes: 4
Views: 7829
Reputation: 2452
You're using AddMaps
when you shouldn't be. AddMaps
just adds profiles and mappings, but doesn't add all the extra services that the DI package does.
This will do it properly:
services.AddAutoMapper(typeof(TestProfile).Assembly);
Now, AutoMapper gives you a very unhelpful error here, but the issue goes back to Microsoft Dependency injection. The DI doesn't know about your custom resolver type, so it doesn't even try.
Since you didn't use the DI package's extension method, the resolver doesn't get added to the service collection. You can manually add these services if needed:
services.AddAutoMapper(cfg => cfg.AddMaps(typeof(TestProfile).Assembly));
services.AddTransient<CustomResolver>();
Upvotes: 10