AutoMapper Custom Resolver asking for optional parameters in constructor

一个人想着一个人 提交于 2021-01-04 08:38:49

问题


I am having some issues with a custom resolver in AutoMapper. I am passing in a interface to the constructor of my repository but i keep getting the following error:

Type needs to have a constructor with 0 args or only optional args
Parameter name: type

I can get around it by creating a parameter-less constructor and hard coding the concrete implementation of my repo in there, but i want to inject it.

My Resolver:

public class OptionGroupProjectionResolver : ValueResolver<Product, List<OptionGroupProjection>>
{
    private readonly IOptionGroupRepository _optionGroupRepository;

    public OptionGroupProjectionResolver(IOptionGroupRepository optionGroupRepository)
    {
        _optionGroupRepository = optionGroupRepository;
    }

    protected override List<OptionGroupProjection> ResolveCore(Product source)
    {
        var groupIds = new List<int>();
        var optIds = new List<int>();

        foreach (var variant in source.Variants)
        {
            groupIds.AddRange(variant.Options.Select(option => option.GroupId).Distinct());
            optIds.AddRange(variant.Options.Select(option => option.Id).Distinct());
        }

        var groups = _optionGroupRepository.GetAll();

        var results = from gr in groups
                      where groupIds.Contains(gr.Id)
                      select new OptionGroupProjection
                      {
                          Id = gr.Id,
                          Name = gr.Name,
                          Options = gr.Options.Where(o => optIds.Contains(o.Id)).ToList()
                      };

        return results.ToList();
    }
}

Ninject Config for Repo

_kernel.Bind<IOptionGroupRepository>().To<OptionGroupRepository>();

Mapping Config

        Mapper.CreateMap<Product, ProductDetailsViewModel>()
            .ForMember(
                dest => dest.DefaultImage,
                opt => opt.MapFrom(src => src.Images.OrderBy(i => i.SortOrder).FirstOrDefault())
            )
            .ForMember(
                dest => dest.SelectOptionGroups,
                opt => opt.ResolveUsing<OptionGroupProjectionResolver>()
            );

I can't really see what i can do, i am sure i have set something up wrong by my Google skills are failing me today.


回答1:


Inside of your bootstrapping/initialization code, you need to tell AutoMapper how to resolve dependencies. I haven't used Ninject, but it might be something like this:

AutoMapper.Mapper.Configuration.ConstructServicesUsing(t => _kernel.Get(t));

The lambda is what AutoMapper will execute to resolve dependencies at runtime.



来源:https://stackoverflow.com/questions/23525853/automapper-custom-resolver-asking-for-optional-parameters-in-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!