Refactor over C# code to implement some kind of Factory Design Pattern

I have a Web API App (.NET Core) that is part of my backend. I have implemented the Unit of Work and Repository patterns into a N-Layer 1 Tier Architecture. The way how the Client App and the backend communicate is through sending DTO's (Data Transfer Objects). So, I have different DTO's obviously with a different structure and composition according to what the Repository Method is requesting. This is because at design time I define the type of DTO the Client is expecting, something like this:

public EmployeeDto GetEMployeeDto()
{
    public EmployeeDto employee = new EmployeeDto();
    
    .
    .
    .
    \\ Code to get data from data base and full fill the fields of the DTO.
    .
    .
    .

    return EmployeeDto;

}

Where EmployeeDto is something like this:

public cladd EmployeeDto()
{
     public int Employee Id {get;set;}
     public string EmployeeName {get;set;}
}

What I would like to do is remove the instantiating code (public EmployeeDto employee = new EmployeDto();) which is tight coupling, and implement some kind of factory pattern where I just call the Factory object, pass the type of DTO I want (because I already know it) and that the Factory returns me the type of DTO I requested and with the DTO state (data).

Just keep on mind that I have several types of DTO's with different structure, so the way how they are fill is different and that the Factory object could be called in different methods and could be requested different DTO's.

Something like:

var employee = FactoryDto.GetDto(EmployeDto);
var employeeHistory = FactoryDto.GetDto(EmployeeHistoryDto);

With just one line get the whole "package" the DTO itself and the data.

I just need a guidance to which Design Pattern could be the best option and an example, I have read about the Creational Design pattern Factory and the different flavors it has but I have not understood yet how could this achieve.



Read more here: https://stackoverflow.com/questions/64901571/refactor-over-c-sharp-code-to-implement-some-kind-of-factory-design-pattern

Content Attribution

This content was originally published by Paul at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: