Skip to content

Initialize

Bert Loedeman edited this page Aug 26, 2015 · 4 revisions

automapper.initialize

The initialize function initializes the mapper with the supplied configuration. The function takes a single configuration function as parameter. This configuration function is called by the library, providing an IConfiguration object. This object discloses the following main functionality:

addProfile(profile: IProfile): void;
createMap(sourceKey: string, destinationKey: string): IAutoMapperCreateMapChainingFunctions;

In advanced cases, you could have a need to differentiate mapping configuration even further than just creating mappings. One of those cases is a differentiation in naming conventions between source and destination objects (e.g. PascalCase to camelCase property names). In those cases you mapping profiles are to the rescue. In order to make a mapping profile available for mapping, you have to instantiate the mapping profile and add it using the addProfile function. Profiles are an advanced topic with an entire page of their own: check out the profiles page if you want to dive in much deeper.

class CamelCaseToPascalCaseMappingProfile extends AutoMapperJs.Profile {
    public sourceMemberNamingConvention: AutoMapperJs.INamingConvention;
    public destinationMemberNamingConvention: AutoMapperJs.INamingConvention;

    public profileName = 'CamelCaseToPascalCase';
    
    public configure() {
        this.sourceMemberNamingConvention = new AutoMapperJs.CamelCaseNamingConvention();
        this.destinationMemberNamingConvention = new AutoMapperJs.PascalCaseNamingConvention();
    }
}

automapper.initialize((config: AutoMapperJs.IConfiguration) => {
    config.addProfile(new CamelCaseToPascalCaseMappingProfile());
});

Creating mapping configurations using the initialize function is basically identical to creating mapping configurations by directly calling automapper.createMap(). The syntax is here primarily to provide convenient functionality to those already familiar with AutoMapper in .NET.

class Person {
    fullName: string;
    age: number;
}

class ValidatedAgeMappingProfile extends AutoMapperJs.Profile {
    public profileName = 'ValidatedAgeMappingProfile';
    
    public configure() {
        const sourceKey = 'ApiPerson';
        const destinationKey = 'Person';

        this.createMap(sourceKey, destinationKey)
            .forMember('proclaimedAge', (opts: AutoMapperJs.IMemberConfigurationOptions) =>opts.ignore())
            .forMember('age', (opts: AutoMapperJs.IMemberConfigurationOptions) =>opts.mapFrom('ageOnId'))
            .convertToType(Person);
    }
}

const sourceObject = { fullName: 'John Doe', proclaimedAge: 21, ageOnId: 15 };

automapper
    .createMap('ApiPerson', 'Person')
    .withProfile('ValidatedAgeMappingProfile');

var result = automapper.map('ApiPerson', 'Person', sourceObject);

The result of this code will be (JSON notation):

{
    "fullName": "John Doe", 
    "age": 15 
}