Autofac 3 and Automapper

Does anyone know a detailed Automapper setup guide with Autofac. I'm new to both, but I played with the static Mapper class, however, I want to be able to mock and inject IMappingEngine and create a configuration that sets up all my mappings. All the manuals that I looked at until they explain what is happening, and I can not solve it. I also use Autofac 3.0, which seems to have some differences in the ContainerBuilder methods that do not help (the reason I use this depends on Autofac.mvc4).

Update:

OK, the simplest solution seems to work quite well, however, I have not seen it anywhere on the Internet, and perhaps for good reason, what I do not know? The simplest thing is to simply register the static Mapper.Engine as IMappingEngine and still use the static Mapper.CreateMap to configure first.

var builder = new ContainerBuilder(); builder.Register<IMappingEngine>(c => Mapper.Engine); 

Autofac can now introduce IMappingEngine into your constructors. This means that Mapper will handle a plain IMappingEngine, not Autofac, and Autofac just acts as a wrapper for it. I would like Autofac to handle an instance of IMappingEngine, but I'm not sure how?

+4
source share
1 answer

Your simple solution is fine if you don’t want to mock the linker in unit tests or create maps with modified configurations for nested lifetime areas (the latter looks a little strange to me, but who knows).

If you need it, you can take some code snippets from the Mapper class and register the following components:

 builder.Register(ctx => new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers())) .AsImplementedInterfaces() .SingleInstance(); builder.RegisterType<MappingEngine>() .As<IMappingEngine>(); 

I'm not sure if you really need to do IMappingEngine singleton. It should be light enough to create addiction.

Now you can use it as follows:

 // in a bootstrapper: var mapperConfig = ctx.Resolve<IConfiguration>(); mapperConfig.CreateMap<A, B>(); // later on: public class X{ IMappingEngine _mapper; public X(IMappingEngine mapper){ _mapper = mapper; } public B DoSmth(){ return _mapper.Map<B>(new A()); } } 

You can also configure automatic registration of profiles as follows:

 builder.Register(ctx => new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers())) .AsImplementedInterfaces() .SingleInstance() .OnActivating(x => { foreach (var profile in x.Context.Resolve<IEnumerable<Profile>>()){ x.Instance.AddProfile(profile); } }); 

Then simply register the Profile implementation anywhere in the Autofac configuration or in the module to connect it to the configuration.

+10
source

All Articles