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.
source share