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

查看:34
本文介绍了依赖注入 - 与数据传输对象 (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.

问题:

  1. 我们如何在不更新 DTO 或使用服务定位器反模式的情况下创建/使用 DTO?在 Composition Root 中组合一个空的 DTO 对象并通过构造函数将其注入 Service 类并没有多大意义,因为我实际上是在填充列表时将 DTO 用作某种临时变量.

  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.

在代码中,您可以看到我更新 DTO 的示例.但这感觉不多比我首先让 DTO 不实现接口要好.那么他们是否应该不实现接口,从而不将 DI 与 DTO 一起使用?

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

推荐答案

对我来说,将任何 DI 用于 DTO 都没有多大意义.我可能会使用工厂模式为我的模型对象获取 DTO.

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.

DTO 不需要容器管理它们的生命周期;我只想 new 它们.不要过度设计.

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

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

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