如何使用Ninject来注入AutoMapper Mapper代替IMapper?

4

我遇到了依赖注入错误

激活IConfigurationProvider时发生错误: 没有匹配的绑定可用,并且该类型无法自我绑定。 激活路径: 3)将IConfigurationProvider作为参数注入Mapper类型的构造函数中的configurationProvider依赖项 2)将IMapper作为参数注入MyController类型的构造函数中的mapper依赖项 1)请求MyController

我的全局asx

Mapper.Initialize(c => c.AddProfile<MappingProfile>());

我的映射配置文件
    public class MappingProfile : Profile
    {
    public MappingProfile()
    {
        CreateMap<Obj, ObjBO>().ReverseMap();
    }
    }

我的控制器

    private readonly IMapper _mapper;

    public MyController(IMapper mapper)
    {

        _mapper = mapper;
    }

尝试像这样使用映射器:
        IEnumerable<ObjBO> list = _repo.GetObjs();
        IEnumerable <Obj> mappedList= _mapper.Map<IEnumerable<Obj>>(list);

我尝试将此添加到NinjectWebCommons中

                private static void RegisterServices(IKernel kernel)
                {
                   kernel.Bind<IMapper>().To<Mapper>().InRequestScope();
                }

可能是AutoMapper 4.2和Ninject 3.2的重复问题。 - BatteryBackupUnit
1个回答

5
您的绑定已配置为每个请求构造Mapper的新实例,但您已经配置了静态Mapper。以下是类似于我正在使用的配置。
kernel.Bind<IMapper>()
    .ToMethod(context =>
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile<MappingProfile>();
            // tell automapper to use ninject when creating value converters and resolvers
            cfg.ConstructServicesUsing(t => kernel.Get(t));
        });
        return config.CreateMapper();
    }).InSingletonScope();

然后您可以删除静态配置

Mapper.Initialize(c => c.AddProfile<MappingProfile>());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接