ChibaKun
ChibaKun

Reputation: 77

How do I use Ninject to inject AutoMapper Mapper in place of IMapper?

I get this injector error

Error activating IConfigurationProvider No matching bindings are available, and the type is not self-bindable. Activation path: 3) Injection of dependency IConfigurationProvider into parameter configurationProvider of constructor of type Mapper 2) Injection of dependency IMapper into parameter mapper of constructor of type MyController 1) Request for MyController

My global asx

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

My mapping profile

    public class MappingProfile : Profile
    {
    public MappingProfile()
    {
        CreateMap<Obj, ObjBO>().ReverseMap();
    }
    }

My Controller

    private readonly IMapper _mapper;

    public MyController(IMapper mapper)
    {

        _mapper = mapper;
    }

Trying to use the mapper like this

        IEnumerable<ObjBO> list = _repo.GetObjs();
        IEnumerable <Obj> mappedList= _mapper.Map<IEnumerable<Obj>>(list);

I tried adding this to NinjectWebCommons

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

Upvotes: 4

Views: 1882

Answers (1)

efredin
efredin

Reputation: 451

Your bindings are configured to construct a new instance of Mapper for each request, but you've configured a static Mapper. Here's a configuration similar to one I'm using.

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

You can then remove your static configuration

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

Upvotes: 5

Related Questions