Skip to content

Support for classes with private constructor #625

@bahmanbs

Description

@bahmanbs

Is your feature request related to a problem? Please describe.

No response

Describe the solution you'd like

Automapper must accept classes with public constructors, or classes with a private constructor and a specific factory method name determined by Automapper to call and instantiate a new instance and start mapping.

As desribed in the docs we can use ConstructUsing method to call static factory methods but class signature with a private constructor causes an error.

this is an example:

class Source
{
    constructor (private _firstName: string, private _lastName: string)
    { }

    public get firstName()
    {
        return this._firstName;
    }

    public get lastName()
    {
        return this._lastName;
    }
}

class Destination
{
    private _fullName: string;

    private constructor ();
    private constructor (_fullName: string);
    private constructor (...args: any[])
    {
        if (typeof args[ 0 ] == "string")
        {
            this._fullName = args[ 0 ];
        }
    }

    public get fullName()
    {
        return this._fullName;
    }

    public static createForMapping()
    {
        return new Destination();
    }
}

const dataSource = new Source("John", "Doe");

const mapper = createMapper({ strategyInitializer: classes() })

createMap(mapper, Source, Destination,
    forMember((destination) => (destination.fullName), mapFrom((source) => (`${source.firstName} ${source.lastName}`)))
)

image

Describe alternatives you've considered

No response

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions