How to configure Automapper to be injected with Ninject 2.0?

寵の児 提交于 2019-12-05 02:56:57

问题


There are configuration examples for Structure Map and Windsor: http://www.cprieto.com/index.php/2009/08/20/using-automapper-with-castle-windsor/

But I haven't found anything for Ninject.

Do you know how to translate those mappings to Ninject?


回答1:


public class AutoMapperModule : NinjectModule
{
    public override void Load()
    {
        Bind<IMappingEngine>().ToMethod(ctx => Mapper.Engine);
    }
}



回答2:


It's really very easy, just load 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<Configuration>().ToSelf().InSingletonScope()
            .WithConstructorArgument("mappers",
                ctx => ctx.Kernel.GetAll<IObjectMapper>());
        Bind<IConfiguration>().ToMethod(ctx => ctx.Kernel.Get<Configuration>());
        Bind<IConfigurationProvider>().ToMethod(ctx => 
            ctx.Kernel.Get<Configuration>());
        Bind<IMappingEngine>().To<MappingEngine>();
    }
}

A few things to note about this:

  • Instead of just supplying MapperRegistry.AllMappers as the constructor argument to Configuration, it actually goes and binds each individual IObjectMapper and then uses the kernel itself to get the constructor arguments in the WithConstructorArgument binding. The reason for this is so that you can load your own IObjectMapper bindings into the kernel if you decide you want to write your own custom mappers.

  • The reason for self-binding Configuration and then method-binding IConfiguration and IConfigurationProvider is that unlike Windsor, Ninject doesn't provide any first-class support for binding multiple interfaces to a single target scope, hence this hack.

That's really all there is to it. Write your container class with dependencies on IConfiguration (if you want to create new maps) and/or IMappingEngine (to actually do the mapping), and Ninject will inject them without any problems.

If you want to go ultra-loosely-coupled and have every mapping defined in its own class, then you'll probably want to take a look at the Conventions Extension for Ninject, which can do assembly scans similar to Windsor's FromAssembly. This can also load any custom IObjectMapper classes you might define in a separate library.



来源:https://stackoverflow.com/questions/3401303/how-to-configure-automapper-to-be-injected-with-ninject-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!