【问题标题】:How do I use Ninject to inject AutoMapper Mapper in place of IMapper?如何使用 Ninject 注入 AutoMapper Mapper 代替 IMapper?
【发布时间】:2017-04-22 14:47:25
【问题描述】:

我得到这个注射器错误

激活 IConfigurationProvider 时出错 没有匹配的绑定可用,并且该类型不可自绑定。 激活路径: 3)将依赖IConfigurationProvider注入到Mapper类型的构造函数的参数configurationProvider中 2)将依赖IMapper注入MyController类型的构造函数的参数映射器中 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();
                }

【问题讨论】:

标签: asp.net-mvc ninject automapper


【解决方案1】:

您的绑定配置为为每个请求构造一个新的 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>());

【讨论】:

    猜你喜欢
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多