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

前端 未结 3 1276
执念已碎
执念已碎 2020-12-11 04:10

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

相关标签:
3条回答
  • 2020-12-11 04:48

    Have a look at AutoMapper. And I agree with @duffymo, I wouldn't use interfaces with DTO's. AutoMapper is a convention-based object to object mapper that will create and populate your DTO's for you. If nothing else it will save you a lot of typing. I've been through the exercise of writing conversion routines to/from DTO's with associated typos. I wish I had found AutoMapper a bit sooner. In the case of your example (where I've nominally made the "from" object of type Order):

    public class Services : IServices
    {    
        public IList<DTO> GetDTOs()
        {    
            ...
            Mapper.CreateMap<Order, DTO>(); // move map creation to startup routine
            var dtos = new List<DTO>();
            foreach (c in d) 
            {
                dtos.Add( Mapper.Map<Order, DTO>(c));
            }
            return dtos;
         }
    }
    

    Or using LINQ

    public class Services : IServices
    {    
        public IList<DTO> GetDTOs()
        {    
            ...
            Mapper.CreateMap<Order, DTO>(); // move map creation to startup routine
            return d.Select(c => Mapper.Map<Order, DTO>(c)).ToList();
         }
    }
    
    0 讨论(0)
  • 2020-12-11 05:05

    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.

    0 讨论(0)
  • 2020-12-11 05:11

    I don't think DTOs should implement interfaces, because they aren't likely to implement behavior that will change.

    They also shouldn't be injected. Not all objects should be. I think this is an appropriate call to new: create the object, use it, let it go out of scope and be GC'd.

    0 讨论(0)
提交回复
热议问题