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?
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?
public class AutoMapperModule : NinjectModule
{
public override void Load()
{
Bind<IMappingEngine>().ToMethod(ctx => Mapper.Engine);
}
}
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.