Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper with DI: Cannot create an instance of type... When using a ValueResolver

I have a .NET Core 3.1 API with the following Nuget packages:

  • AutoMapper (10.1.1)
  • AutoMapper.Extensions.Microsoft.DependencyInjection (8.1.1)

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?

like image 810
eliasmartinez93 Avatar asked Oct 15 '25 14:10

eliasmartinez93


1 Answers

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>();
like image 145
Adam Schiavone Avatar answered Oct 17 '25 10:10

Adam Schiavone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!