Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automapper ninject dependencies

I have a problem with the Automapper on my website and I can't find a solution. I've created a class called AutoMapperProfile where I'd like to put all my Maps

public class AutoMapperProfile: Profile
{
    private readonly IConfiguration _mapper;

    public AutoMapperProfile(IConfiguration mapper)
    {
        _mapper = mapper;
    }

    protected override void Configure()
    {
        base.Configure();

        _mapper.CreateMap<SlideDTO, Slide>();
        _mapper.CreateMap<Slide, SlideDTO>();
    }
}

For DI purposes I'm using Ninject, so I've added the following bindings in NinjectWebCommon:

kernel.Bind<IMappingEngine>().ToMethod(ctx => Mapper.Engine);
kernel.Bind<IConfigurationProvider>().ToMethod(x => Mapper.Engine.ConfigurationProvider);

The controller looks like this:

private readonly ISlideRepository slideRepository;
    private readonly IMappingEngine mappingEngine;

    public HomeController(
        ISlideRepository slideRepository,
        IMappingEngine mappingEngine)
    {
        this.slideRepository = slideRepository;
        this.mappingEngine = mappingEngine;
    }

    [HttpGet]
    public ActionResult Index()
    {
        var model = new IndexViewModel();
        var slide = slideRepository.GetSlide();
        model.Slide = mappingEngine.Map<SlideDTO, Slide>(slide);

        return View(model);
    }

When I map from SlideDTO to Slide I get the following error:

Missing type map configuration or unsupported mapping.

So my best guess is that I didn't do the binds correctly so that Automapper can see my maps, but I'm not sure how can I fix it.

like image 452
Marian Ene Avatar asked Nov 10 '22 00:11

Marian Ene


1 Answers

You don't need to inject IConfiguration into AutoMapperProfile, it already inherits a CreateMap method from Profile.

Make sure that AutoMapperProfile has a parameterless constructor like this:

public class AutoMapperProfile : Profile
{
    protected override void Configure()
    {
        this.CreateMap<SlideDTO, Slide>();
        this.CreateMap<Slide, SlideDTO>();
    }
}

And then you need to make sure that AutoMapper knows about this profile, here is how you can do it:

Mapper.Engine.ConfigurationProvider.AddProfile<AutoMapperProfile>();

Please note that you can invoke the AddProfile method on any IConfigurationProvider (if you decide not to use the global ConfigurationProvider and Engine).

like image 100
Yacoub Massad Avatar answered Dec 13 '22 22:12

Yacoub Massad