Automapper multiple sources for profiles

1k Views Asked by At

Prior to assembly scanning (circa 4.x) we did something like the following to provide a centralised approach to adding profiles:

/// <summary>
///     Class that allows all the AutoMapper profiles to be initiated for all assemblies within the platform.
/// </summary>
public class OzCpAutoMapperConfig
{
    private Type[] _ExternalProfiles;

    /// <summary>
    ///     For the 201610.02 release we are not using assembly scanning so we get the caller to pass
    ///     in the profiles they want us to register.
    /// </summary>
    /// <param name="aExternalProfiles">List of automapper profile classes that we also need to register</param>
    public void ConfigurationApproachFor201610_02(Type[] aExternalProfiles)
    {
        _ExternalProfiles = aExternalProfiles;
        Mapper.Initialize(DoMapperConfigFor201610_02);
    }

    /// <summary>
    ///     Internal helper method that populates the AutoMapper configuration object.
    /// </summary>
    /// <param name="aMapperConfiguration">Instance of AutoMapper configuration object that we need to use.</param>
    private void DoMapperConfigFor201610_02(IMapperConfiguration aMapperConfiguration)
    {
        //Add all the external mapper configurations passed in by the original caller
        foreach (Type externalProfile in _ExternalProfiles)
        {
            aMapperConfiguration.AddProfile(Activator.CreateInstance(externalProfile) as Profile);
        }

        //Now add all the platform profiles
        aMapperConfiguration.AddProfile<CarnivalApiServiceAutoMapperProfile>();
        aMapperConfiguration.AddProfile<CarnivalOpenseasApiServiceAutoMapperProfile>();
        ...
   }
}

So now with 5.2 we want to use the assembly scanning AND be able to pass in some additional profiles to register. However IMapperConfiguration is no longer available. So while I could do:

Mapper.Initialize(cfg => { cfg.AddProfiles("MyNameSpace.Application", "MyNameSpace.Core", ....); 

how do I add the additional profiles I want included as part of the Mapper.Initialize() call? (They are not in the assemblies to be scanned).

1

There are 1 best solutions below

0
On

IMapperConfiguration was renamed to IMapperConfigurationExpression in 5.2. So the same approach described above can be used after using the renamed interface.