IoC with AutoMapper Profile Using Autofac

I have been using AutoMapper for some time now. I have this profile setting:

public class ViewModelAutoMapperConfiguration : Profile { protected override string ProfileName { get { return "ViewModel"; } } protected override void Configure() { AddFormatter<HtmlEncoderFormatter>(); CreateMap<IUser, UserViewModel>(); } } 

I add this to the mapper using the following call:

 Mapper.Initialize(x => x.AddProfile<ViewModelAutoMapperConfiguration>()); 

However, now I want to pass the dependency to the ViewModelAutoMapperConfiguration constructor using IoC. I am using Autofac. I read the article here: http://www.lostechies.com/blogs/jimmy_bogard/archive/2009/05/11/automapper-and-ioc.aspx , but I don’t see how this will work with profiles.

Any ideas? Thanks

+2
source share
2 answers

Well, I found a way to do this using AddProfile overloading. There is an overload that accepts an instance of the profile, so I can resolve the instance before passing it to the AddProfile method.

+1
source

My client was interested in the same as DownChapel and his answer called me in writing as an example application.

I did the following. First, extract all Profile types from asseblies and register them in the IoC container (I use Autofac).

 var loadedProfiles = RetrieveProfiles(); containerBuilder.RegisterTypes(loadedProfiles.ToArray()); 

When registering an AutoMapper configuration, I enable all Profile types and allow them to be an instance.

 private static void RegisterAutoMapper(IContainer container, IEnumerable<Type> loadedProfiles) { AutoMapper.Mapper.Initialize(cfg => { cfg.ConstructServicesUsing(container.Resolve); foreach (var profile in loadedProfiles) { var resolvedProfile = container.Resolve(profile) as Profile; cfg.AddProfile(resolvedProfile); } }); } 

Thus, your IoC-framework (Autofac) will resolve all Profile dependencies, so it may have dependencies.

 public class MyProfile : Profile { public MyProfile(IConvertor convertor) { CreateMap<Model, ViewModel>() .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Identifier)) .ForMember(dest => dest.Name, opt => opt.MapFrom(src => convertor.Execute(src.SomeText))) ; } } 

The full sample application can be found on GitHub , but most of the important code is used here.

0
source

All Articles