依赖注入 - 使用数据传输对象(DTO)? [英] Dependency Injection - use with Data Transfer Objects (DTOs)?
问题描述
问题:
-
我们是否创建/使用DTO而不新建或使用服务定位器反模式?在组合根中组合一个空的DTO对象并通过构造函数将其注入到Service类中是没有意义的,因为我实际上将DTO用作一个填充列表的临时变量。 p>
-
在代码中,您可以看到我新建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:
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.
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屋!