依赖注入 - 使用数据传输对象(DTO)? [英] Dependency Injection - use with Data Transfer Objects (DTOs)?

查看:174
本文介绍了依赖注入 - 使用数据传输对象(DTO)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的代码(已被简化)。我有一个服务类,返回一个特定DTO对象的列表,每个对象实现自己的特定接口。在实际的代码中,我们正在使用遗留代码,通过对数据集进行迭代来填充这些代码。



问题:


  1. 我们是否创建/使用DTO而不新建或使用服务定位器反模式?在组合根中组合一个空的DTO对象并通过构造函数将其注入到Service类中是没有意义的,因为我实际上将DTO用作一个填充列表的临时变量。 p>


  2. 在代码中,您可以看到我新建DTO的示例。但是,如果我的DTO没有实现接口,那么这不会比bbb更好。那么他们应该不会实现接口,因此,不要使用DI与DTO?







  public class Services:IServices 
{
public IList< IDTO> GetDTOs()
{
...
列表< 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;
}
}


解决方案

对于DTO来说,使用DI来没有什么意义。我可能会使用Factory Pattern来为我的模型对象获取DTO。



DTO不需要由容器管理的生命周期;我只是新的他们。不要过度工程。


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;
    }    
}

解决方案

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.

这篇关于依赖注入 - 使用数据传输对象(DTO)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆