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

前端 未结 3 1277
执念已碎
执念已碎 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 GetDTOs()
        {    
            ...
            Mapper.CreateMap(); // move map creation to startup routine
            var dtos = new List();
            foreach (c in d) 
            {
                dtos.Add( Mapper.Map(c));
            }
            return dtos;
         }
    }
    

    Or using LINQ

    public class Services : IServices
    {    
        public IList GetDTOs()
        {    
            ...
            Mapper.CreateMap(); // move map creation to startup routine
            return d.Select(c => Mapper.Map(c)).ToList();
         }
    }
    

提交回复
热议问题