Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection - use with Data Transfer Objects (DTOs)?

Consider the code below (which has been simplified). I have a service class that returns a list of specific DTO objects that each implement their own specific interface. In the actual code these are getting populated by iterating thru a Dataset as I'm working with legacy code.

Questions:

  1. How do we create/use a DTO without newing them up or using the Service Locator anti-pattern? It doesn't make much sense to compose an empty DTO object in the Composition Root and inject it into the Service class via the constructor, because I'd actually be using the DTO as a temporary variable of sorts while populating a list.

  2. In the code you can see an example of me newing up the DTO. But this doesn't feel much better than if I made the DTOs not implement interfaces in the first place. So should they not implement interfaces then and thus, not use DI with DTOs?


public class Services : IServices
{    
    public IList<IDTO> GetDTOs()
    {    
        ...
        List<IDTO> dtos = new List<IDTO>();
        foreach (c in d) 
        {
            DTO dto = new DTO();
            dto.x = c.x;
            dto.y = c.y;
            dto.z = c.z;
            dtos.Add(dto);
        }
        return dtos;
    }    
}
like image 852
Matt Avatar asked Jun 09 '11 18:06

Matt


1 Answers

it doesn't make much sense to me to use any DI for DTOs. I would probably use the Factory Pattern to get DTOs for my model objects.

DTOs don't need their life cycle managed by the container; I would just new them. Dont over-engineer.

like image 99
hvgotcodes Avatar answered Nov 22 '22 17:11

hvgotcodes