C#构造函数DTO和依赖注入 [英] C# Dto constructor and dependency injection

查看:1952
本文介绍了C#构造函数DTO和依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是设计DTO对象的构造函数的最佳实践

I would like to know what is the best practice in designing the constructors of DTO objects.

说我有一个DTO对象是这样的:

say i have a Dto object like this:

class CustomerDto
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Phone { get; set; }
    ...
}

有多种方法来构造对象

我可以宣布一个构造函数:

I could declare a constructor:

public CustomerDto(string name, string surname, string phone, ...)
{
    this.Name = name;
    this.Surname = surname;
    this.Phone = phone;
    ...
}

当你看到这个构造,并立即签订SRP(单一职责)违反?

When you see this constructor and immediately conclude a SRP (Single responsibility) violation?

尽管这些属性都有关。

我们也可以争论有无需验证的属性,因为这是一个DTO并具有NO行为,而行为而应是域对象,这从地图上。

One could also argue there is no need to validate the properties as this is a DTO and has NO behavior, and the behavior should rather be on the domain object that this maps from.

在C#中,我们也可以更优雅的构造这个对象:

In C# we can also more elegantly construct this object:

var dto = new CustomerDto ()
{
    Name = "Some name",
    Surname = "Some surname"
}

或用一口流利的建设者或诸如NBuilder一个框架。

Or use a fluent builder or a framework such as NBuilder.

还有像Automapper自动映射框架的使用。这个问题还使用一个IoC容器构造函数变得复杂,以及在交换参数,例如风险,你的名字,其中姓反之亦然通过,验证可能会错过如上所述,这更容易然后明确的映射。

There is also the usage of Auto mapping frameworks like Automapper. The problem is also using an Ioc container the ctor becomes complex, as well as the risk in swapping arguments for example, you pass in name where surname is or vice versa, the validation could miss this more easy then explicit mapping as above.

请帮助说服我这是更好的办法。

Please help convince me which is the better way.

推荐答案

值类型如在实施例不依赖关系。依赖关系提供了一个功能(或配置)给消费者。在你的情况下,他们是分配给您的DTO只是正常值。只要数据属于你一起不违反SRP,即使你在构造函数中分配了大量的值。在这种情况下,单一的责任是保持数据

Value types as in your examples aren't dependencies. A dependency provides a functionality (or configuration) to the consumer. In your case they are just normal values that are assigned to your DTO. As long as the data belongs together you do not violate SRP even if you assign a lot of values in the constructor. The single responsibility in this case is to hold the data.

另外DTO的不应由一个IoC容器创建,并没有真正的依赖关系。您应该手动创建它们,你的持久性框架或使用自动映射。

Also DTO's shouldn't be created by a IoC container and have no real dependencies. You should create them manually, by your persistency framework or using auto mapping.

如果使用的是构造函数或属性分配值更好取决于使用情况。如果它们需要构造变体是更好。如果它们是可选的财产的方式比较好。

If assigning the values using a constructor or properties is better depends on the usage. If they are required the constructor variant is better. If they are optional the property way is better.

这篇关于C#构造函数DTO和依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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