Autofac / Automapper-自定义值解析器错误

时间:2019-07-11 14:29:30

标签: automapper autofac

Autofac注册:

builder.RegisterType<RelatedTransportMangerResolver>().AsSelf();
builder.Register(context => new MapperConfiguration(cfg =>
{
    cfg.AddProfile<AssetMapperProfile>();
})).AsSelf().SingleInstance();

builder.Register(c => c.Resolve<MapperConfiguration>().CreateMapper(c.Resolve))
.As<IMapper>()
.InstancePerLifetimeScope();

使用自定义值解析器的地图:

CreateMap<TrafficArea, TrafficAreaViewModel>()
            .ForMember(ta => ta.TransportManagers,
                opt => opt.MapFrom(ta =>
                    ta.TrafficAreaKeyContacts
                        .Where(kc => kc.KeyContactGroup.HasFlag(KeyContactGroup.TransportManager))
                        .Select(atr => atr.KeyContact)))
            .ForMember(ta => ta.RelatedTransportManagers,
                opt => opt.MapFrom<RelatedTransportMangerResolver>());

返回的错误是:

  

此解析操作已结束。使用lambda注册组件时,无法存储IComponentContext'c'参数到lambda。而是从'c'再次解析IComponentContext,或从基于Func <>的工厂解析以从中创建后续组件。

关于如何解决此错误的任何想法?

1 个答案:

答案 0 :(得分:0)

应该先多挖一点自己的东西...

如果有人遇到相同问题,请在此处修复:

builder.Register(c =>
{
    //This resolves a new context that can be used later.
    var context = c.Resolve<IComponentContext>();
    var config = context.Resolve<MapperConfiguration>();
    return config.CreateMapper(context.Resolve);
})
.As<IMapper>()
.InstancePerLifetimeScope();