问题
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.AllMappersas the constructor argument toConfiguration, it actually goes and binds each individualIObjectMapperand then uses the kernel itself to get the constructor arguments in theWithConstructorArgumentbinding. The reason for this is so that you can load your ownIObjectMapperbindings into the kernel if you decide you want to write your own custom mappers.The reason for self-binding
Configurationand then method-bindingIConfigurationandIConfigurationProvideris 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