Sam
Sam

Reputation: 1692

Map DTO to Base Model with protected constructor

All my model classes have one public constructor that takes a session / unit of work object (required by the ORM I am using). However, they also inherit from a common base class XPObject with a protected constructor that requires this session object like so

public class XPObject
{
    protected XPObject(Session session) { ... }
}

public class Person
{
    public Person(Session session) : base(session) { ... }
}

The DTOs in turn all inherit from the common base class EntityDto which has a default constructor.

My mappings are something like the following

cfg.CreateMap<PersonDto, Person>();

When I try to map a DTO to a new object like

mapper.Map<Person>(dto);

I will get the expected error, that the object cannot be created because it has no empty constructor.

I tried to configure the mapper to solve this by using the ForCtorParam option:

CreateMap<EntityDto, XPObject>()
                .DisableCtorValidation()
                .ForCtorParam("session", _ => _.MapFrom((dto, ctx) => ctx.Mapper.ServiceCtor(typeof(UnitOfWork))))
                .IncludeAllDerived();

Unfortunately this fails because the constructor of the XPObject class is protected.

How can I solve this issue without having to configure the CtorParam for each mapping individually?

Upvotes: 2

Views: 327

Answers (0)

Related Questions