C# Dto constructor and dependency injection

后端 未结 2 815
鱼传尺愫
鱼传尺愫 2021-01-11 12:17

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

say i have a Dto object like this:

class CustomerDto
{
          


        
相关标签:
2条回答
  • 2021-01-11 12:51

    I would suggest using immutable data structures so DTO entity would not expose any setters, obviously in this way constructor should provide ability to initialize all underlying properties of a given DTO.

    So I prefer:

    public CustomerDto(string name, string surname, string phone, ...) 
    

    DTO is a Data Transfer Object, especially to represent a set of properties to be passed across a system (distributed as well) boundaries, so do not bother too much regarding SRP violation. This is like Facade design pattern, it abstarcts a set of operations/services to simplify usage. So in this kase Keep It Simple won.

    0 讨论(0)
  • 2021-01-11 13:00

    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.

    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.

    0 讨论(0)
提交回复
热议问题