1
votes

we are starting a new mulit-tier-architecture. In the past I used AutoMapper to map data transfer objects to business objects and vice versa. A colleague suggested that instead of mapping, we should wrapp the dto inside the business object. Probably by injecting the dto in the business object's constructor. Then we can access the dto's propery values on the fly without mapping.

Question:

Is this approach recommended?

I am aware that if the business object knows the dto you introduce tight coupling. Furthermore you loose some flexibility by creating a 1:1 relationship between business object and dto which normally - with flexible mapping - would be a n:m relationship.

(see: Best Practices For Mapping DTO to Domain Object?)

Is this drawback the reason nobody seems to use the wrapper approach or do I miss someting?

Here is a quick demo what I mean with "wrapping":

public class BusinessObject
{
    private Dto dto;

    public BusinessObject()
    {
        this.dto = new Dto();
    }

    public BusinessObject(Dto dto)
    {
        this.dto = dto;
    }


    public int Id
    {
        get { return dto.Id; }
        set { dto.Id = value; }
    }
}

public class Dto
{
    public int Id { get; set; }
}

hanks for your help!

Torsten

1

1 Answers

0
votes

It is a controversial one. I first saw this approach in this blog post.

The benefit is clear. It really simplifies and streamlines your code. Now your business objects (POCOs) do not have to recreate a bunch of accessors and mutators that are already covered by the DTO and instead can just reference the properties of the DTO. Creating business objects is also much easier since you just have to pass in the DTO to the business object constructor and persisting business objects is now much easier since you just need to grab the DTO portion of the object.

There are some drawbacks to this approach. As you pointed out, you are more or less pinned down to a 1-1 mapping now. Another drawback is that you are losing out on any validation or business logic that your business objects may enforce over certain properties of your object (since the DTO now owns them).

A rather large drawback to stuffing the DTO into the business object (POCO) is the sort of behavior it can leave in the code where objects tend to no longer manage their own state. As expressed here, this can make locating the code responsible for specific functionality quite a bit more difficult. It also makes utilizing the classes a bit more hazardous as objects have their state set externally.