C# – SOLID Application Structure and Design

cdesign-patternssolid

A one possible structure for an application is to have it broken down into modules such as Data Access, Core, Services, UI. Now depending on what type of ORM you are using Data Access layer will have a set of entities that represent the tables in the database. The core layer will have a set of entities that represent the business logic. The service layer will have a set of DTO entities that it will communicate with to the UI. And finally the UI will have a set of View Models that it will use inside the views.

Now when we access or store information in the database we have to transform objects from one type to another. When the service calls the core it needs to transform objects from one type to another and finally the UI needs to transform the DTO's to View Models. In a lot of the cases the transformation is a simple act of copying the properties from one object to another. It is a very repetitive and time consuming task that generates large amounts of code.

My question is am I doing something wrong here. Should I only have one entity type? If so don't you think that it would have too much information in one object for data access, business logic etc… Is there a quick way to copy the properties between objects? Reflection is an option but gets complicated fast when dealing with object graphs? I know there is no silver bullet to fix this problem but there must be a number of good approaches over copying the properties by hand between the entities?

Best Answer

I hate the idea of parallel object hierarchies just for the sake of layer purity.

This is a Core J2EE Pattern that in my view has become an anti-pattern. People used to create DTOs because the EJB 1.0 entity model was too chatty. I think POJOs/POCOs are smarter and don't have to resort to such contortions.

The data access layer might represent tables or objects, depending on which way you go.

The service layer maps to use cases and units of work. It owns transactions and orchestrates processes to fulfill the wishes of clients. It should be UI agnostic.

I'd recommend creating model objects and using them appropriately. Just make sure that you find a way to avoid cyclic dependencies between packages/namespaces. Don't couple all of them together. Data access layer should know about model objects but nothing else. Service layer should know about data access layer, model objects, other services and nothing else. View layer should have controllers that invoke services and nothing else.