Home > Back-end >  What is the best architecture for several DTO's to be called by the same method
What is the best architecture for several DTO's to be called by the same method

Time:01-04

I am projecting API, where I have 1 controller and several services for preparing some kinds of reports. Let's say it's ReportA, ReportB and ReportC. All services inherit from abstract class ReportBase, where I have some methods common for all services, fe. GetTotalUsage, which download data from database before calculating the report.

Now it is the tricky part:

method GetTotalUsage use the ReportARequestDto, but I would like to make it take any kind of the DTO (also ReportBRequestDto and ReportCRequestDto).

All DTO's have common properties (StationId,MediaName,DateTimeRange) and some unique.

I could make base class for all DTO's and inherit from it, but it's not a best solution, since I may need to modify and use different properties in the future for another method.

The composite pattern makes the DTO's complex.

What is the most appropiate aproach?

CodePudding user response:

You could make a base DTO class with propety indicating the concrete type of the specific report DTO. This property would be later used to deserialize base class to specific report DTO when needed.

It could look something like this:

class BaseReport {
    abstract string ReportType {get;set;}
    ...
}

class ReportA : BaseReport {
   string ReportType => "ReportA";
   ....
}

CodePudding user response:

are you looking for something like this? you can use a generic type parameter for the GetTotalUsage method.

public abstract class ReportBase
{
    public abstract void GetTotalUsage<T>(T dto) where T : ReportBaseDTO;
}

public abstract class ReportBaseDTO
{
    public int StationId { get; set; }
    public string MediaName { get; set; }
    public DateTimeRange DateTimeRange { get; set; }
}

public class ReportARequestDto : ReportBaseDTO
{
    // more properties specific to ReportA
}

public class ReportBRequestDto : ReportBaseDTO
{
    ///
}

public class ReportCRequestDto : ReportBaseDTO
{
    /// 
}

and call like this?

ReportA reportA = new ReportA();
ReportARequestDto dto = new ReportARequestDto();
reportA.GetTotalUsage(dto);
  • Related