AutoMapper自定义解析器在构造函数中询问可选参数

时间:2014-05-07 18:46:19

标签: c# automapper

我在AutoMapper中遇到自定义解析器的一些问题。我传递的接口到我的存储库的构造函数,但我不断收到以下错误:

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

我可以通过创建一个无参数构造函数并在那里硬编码我的repo的具体实现来解决它,但我想注入它。

我的解析器:

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();
    }
}

Repo的Ninject配置

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

映射配置

        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>()
            );

我无法真正看到我能做些什么,我确信我已经设置了一些错误,我的谷歌技能今天让我失望。

1 个答案:

答案 0 :(得分:7)

在bootstrapping /初始化代码中,您需要告诉AutoMapper如何解决依赖关系。我没有使用Ninject,但它可能是这样的:

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

lambda是AutoMapper在运行时解析依赖关系所要执行的。