简体   繁体   中英

Automapper multiple sources for profiles

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).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM