Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AutoMapper.Profile for creating an instance(non-static) mapper

I use the following method as described in the following answer to create an instance of a mapper:

var platformSpecificRegistry = AutoMapper.Internal.PlatformAdapter.Resolve<IPlatformSpecificMapperRegistry>();
platformSpecificRegistry.Initialize();

var autoMapperCfg = new AutoMapper.ConfigurationStore(new TypeMapFactory(), AutoMapper.Mappers.MapperRegistry.Mappers);
var mappingEngine = new AutoMapper.MappingEngine(_autoMapperCfg);

As described by the following question:

AutoMapper How To Map Object A To Object B Differently Depending On Context.

How would I be able to use[reuse] an Automapper profile class like the following to create an instance of a mapper?

public class ApiTestClassToTestClassMappingProfile : Profile
{
    protected override void Configure()
    {
        base.Configure();
        Mapper.CreateMap<ApiTestClass, TestClass>()
            .IgnoreAllNonExisting();
    }
}

Just to give you an idea on why I require such functionality: I register all Automapper Profile classes into my IoC container [CastleWindsor] using the following method :

    IoC.WindsorContainer.Register(Types.FromThisAssembly()
                                       .BasedOn<Profile>()
                                       .WithServiceBase()
                                       .Configure(c => c.LifeStyle.Is(LifestyleType.Singleton)));

    var profiles = IoC.WindsorContainer.ResolveAll<Profile>();

    foreach (var profile in profiles)
    {
        Mapper.AddProfile(profile);
    }

    IoC.WindsorContainer.Register(Component.For<IMappingEngine>().Instance(Mapper.Engine));

While above completely fulfills the need for initializing my static Mapper class, I really dont have any idea how to re-use my Automapper profile classes for creating instance mappers [using non-static mapper].

like image 667
MHOOS Avatar asked Mar 16 '15 15:03

MHOOS


1 Answers

This is how you create MapperConfiguration with profiles

public static class MappingProfile
{
    public static MapperConfiguration InitializeAutoMapper()
    {
        MapperConfiguration config = new MapperConfiguration(cfg =>
        {
            cfg.AddProfile(new WebMappingProfile());  //mapping between Web and Business layer objects
            cfg.AddProfile(new BLProfile());  // mapping between Business and DB layer objects
        });

        return config;
    }
}

Profiles examples

//Profile number one saved in Web layer
public class WebMappingProfile : Profile
{
    public WebMappingProfile()
    {
        CreateMap<Question, QuestionModel>();
        CreateMap<QuestionModel, Question>();
        /*etc...*/
    }
}

//Profile number two save in Business layer
public class BLProfile: Profile
{
    public BLProfile()
    {
        CreateMap<BLModels.SubModels.Address, DataAccess.Models.EF.Address>();
        /*etc....*/
    }
}

Wire automapper into DI framework (this is Unity)

public static class UnityWebActivator
{
    /// <summary>Integrates Unity when the application starts.</summary>
    public static void Start()
    {
        var container = UnityConfig.GetConfiguredContainer();
        var mapper = MappingProfile.InitializeAutoMapper().CreateMapper();
        container.RegisterInstance<IMapper>(mapper);

        FilterProviders.Providers.Remove(FilterProviders.Providers.OfType<FilterAttributeFilterProvider>().First());
        FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container));

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

        // TODO: Uncomment if you want to use PerRequestLifetimeManager
        // Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule));
    }

    /// <summary>Disposes the Unity container when the application is shut down.</summary>
    public static void Shutdown()
    {
        var container = UnityConfig.GetConfiguredContainer();
        container.Dispose();
    }
}

Use IMapper in you class for mapping

public class BaseService
{
    protected IMapper _mapper;

    public BaseService(IMapper mapper)
    {
        _mapper = mapper;
    }

    public void AutoMapperDemo(){
        var questions = GetQuestions(token);
        return _mapper.Map<IEnumerable<Question>, IEnumerable<QuestionModel>>(questions);
    }

    public IEnumerable<Question> GetQuestions(token){
        /*logic to get Questions*/
    }
}

My original post can be found here: http://www.codeproject.com/Articles/1129953/ASP-MVC-with-Automapper-Profiles

like image 143
xszaboj Avatar answered Nov 10 '22 10:11

xszaboj