问题
I am currently at the beginning of developing a large web application mainly containing an Angular SPA and an OData WebAPI that has access to a backend layer.
We're at an early stage and have begun to implement the first classes including a Model.dll
that is in a common namespace so that it can be accessed by all layers.
We are now discussing about those DTOs within the model. Some say that using interfaces is absolutely neccessary, so the code would be like this:
namespace MySolution.Common.Model
{
public interface IPerson
{
int Id { get; set; }
string Name { get; set; }
...
}
}
namespace MySolution.Common.Model
{
public class PersonDTO : IPerson
{
public int Id { get; set; }
public string Name { get; set; }
...
}
}
So that's it. Just simple DTOs with no more intelligence.
I am now asking myself if this is really a good approach, because I don't see the necessity of using the interface here.
What are the advantages with this? Testability was mentioned, but is it even necessary to test DTos? Dependency Injection should also not the point.
Any enlightenment would be very helpful. At the end learning new stuff and approaches is always good...
回答1:
DTOs transfer state - that's it. Injecting them via a container or mocking them for testing seems pointless (if that's the motivation) and totally unnecessary. Don't do it.
回答2:
As an example, further to my comment above:
Interface IRepo
{
Person GetPerson(int id);
}
Public class DbRepo : IRepo
{
public Person GetPerson(int id){//get person from database}
}
Public class FakeRepo : IRepo
{
public Person GetPerson(int id)
{
return new Person {Id = id, Name = "TestName"};
}
}
You would use a FakeRepo
with some mock objects for testing purposes.
来源:https://stackoverflow.com/questions/30331067/interfaces-for-dtos