Injecting AutoMapper dependencies using Ninject

左心房为你撑大大i 提交于 2019-12-03 07:08:43

You can do this is a one liner using the latest version (currently 2.2.0).

kernel.Rebind<IMappingEngine>().ToMethod(context => Mapper.Engine);

As an extra, I do agree with fodonnel, adding a facade to hide the Automapper interface is a good idea, however I wouldn't take the signatures directly from Automapper, unless you need all that functionality.

It might also be a good idea to introduce a mapping facade. Instead of passing IMappingEngine through out your code create an IObjectMapper interface. The interface I use contains method signatures taken directly out of automappers code.

public interface IObjectMapper
{ 
  TDestination Map(TSource source);
  TDestination Map(TSource source, TDestination destination);
  object Map(object source, Type sourceType, Type destinationType);
  object Map(object source, object destination, Type sourceType, Type destinationType);
}

Your configuration is still going to be automapper dependent.

A blog post I wrote on it is here: http://fodonnel.wordpress.com/2010/09/20/an-object-mapper-facade/

I got it working but it doesn't feel very clean creating an instance of the Configuration class. Any suggestions to clean it up further.

        Bind<ITypeMapFactory>().To<TypeMapFactory>();
        Bind<Configuration>().ToConstant(new Configuration(Kernel.Get<ITypeMapFactory>(), MapperRegistry.AllMappers())).InSingletonScope();
        Bind<IConfiguration>().ToMethod(c => c.Kernel.Get<Configuration>());
        Bind<IConfigurationProvider>().ToMethod(c => c.Kernel.Get<Configuration>());
        Bind<IMappingEngine>().To<MappingEngine>();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!