AutoMapper with Ninject confusion

2019-07-05 09:22发布

问题:

For starters I'm using this module:

    public class AutoMapperModule : NinjectModule
{
    public override void Load()
    {
        Bind<ITypeMapFactory>().To<TypeMapFactory>();
        foreach (var mapper in MapperRegistry.AllMappers())
        {
            Bind<IObjectMapper>().ToConstant(mapper);
        }

        Bind<AutoMapper.ConfigurationStore>().ToSelf().InSingletonScope().WithConstructorArgument("mappers", ctx => ctx.Kernel.GetAll<IObjectMapper>());
        Bind<IConfiguration>().ToMethod(ctx => ctx.Kernel.Get<AutoMapper.ConfigurationStore>());
        Bind<IConfigurationProvider>().ToMethod(ctx => ctx.Kernel.Get<AutoMapper.ConfigurationStore>());
        Bind<IMappingEngine>().To<MappingEngine>();
    }
}

I have a bootstrapper class for all my maps

        public static void Configure(IKernel kernel)
    {
        Mapper.Initialize(map => map.ConstructServicesUsing(t => kernel.Get(t)));
    }

I have resolvers that access the database and need the repositories injected. It's working as is, but I can't figure out how to get it to work with unit tests and IMappingEngine.

        public HomeController(IMappingEngine mappingEngine)
    {
        _mappingEngine = mappingEngine;
    }

_mappingEngine.Map throws an exception because no map exists. Mapper.Map works.

What am I missing? How do I get my bootstrapper to work with unit tests so that the repositories in my resolvers to use the fake/mock repositories?

回答1:

Try changing the mapping's bind.

Bind<IMappingEngine>().ToMethod(ctx => Mapper.Engine);