C#-DDD: Which layer DTO belong into? - c#

I am a new comer in DDD concepts and I am trying to design a solution structure strictly follow DDD & Prism (WPF).
I am stacking at where to create DTO project (Data Transfer Object). As I know, DDD will have 4 general layer:
Presentation
Application
Domain
Infrastructure
So that, would you please tell me which layer for the DTO project belong to?
I have refered at: DDD - which layer DTO should be implemented
Some one told that we should implement it at Service layer, but I think It is not make sense, cause of follow DDD concept, we don't have which called Service layer.
Thank you so much,
Regards

Generally speaking, the location of the component's code should stay besides the owner of that component. The owner has full control of its components. This idea follows the dependency inversion principle.
So,in your case, who is the owner of the DTO? Who controls the structure and the purpose of that DTO?
Using DDD (in any architecture!) you should, however, take into account that domain code should not depend on infrastructure, application or UI code. So, if you decide to put the DTO class into the application layer then you cannot refer to that DTO from your domain code (i.e. a domain entity or a domain service cannot have any references to the DTO class - no import or use directive or new statements)

You might be disturbed by my answer, but I have to repeat again:
Domain-Driven Design is not about layers. It is about Domain and Design.
Domain is your problem space. This is what your users need. This is what your domain experts tell you to do.
Design is how you model your solution. It starts from the knowledge you got by speaking to domain experts. It continues with deciding what are your bounded contexts and how they are placed on the context map. Then you decide how to implement each context - would this be a Domain Model, Active Record, CRUD or some off-the-shelf software.
When you decided on the implementation, you can think of the internal structure and DDD does not dictate anything there.
If your question is where to put DTO for the data - well, they might be located in a separate project if more than one other project uses them, or you put them to the DAL (which is typical) since your presentation layer will most probably use it directly, without involving the domain model, otherwise you won't be mentioning DTOs at all.
Concerning using the term DDD for your question, I wrote a blog post some time ago, targeting this issue, which you might want to read.

I see that we should add DTO classes in the layer will create objects of them to send their to another layer.
In DDD model the Application layer and Infrastructure layer already can access the Domain layer so they don't need DTOs in the infrastructure layer because it will return entity class.
Based on the above we need DTOs to represent the data retrieved from the DB(through Infrastructure layer) in the Application layer and send these data using DTOs to the Presentation layer without making Presentation layer get access the domain entities which are contained in the Domain model layer.
Finally, from my experience and using the DDD model I prefer to add DTOs in a separate project inside the Application layer. which means it belongs to the Application layer.
You can see the sample of my project and the "Core layer" in it means the "Domain Layer"
Also you can read Excellent detailed explanation for DDD model from Microsoft

Related

Enterprise Application in .NET

can you give me some hit or give me explanation how to create Enterprise App in .net, and how projects type use or how should be structure of this projects? I newbie in EE and I read about it, but for me is the best explanation on real world example. My idea about EE solution structure in .net is that:
Data Tier (project type => class library)
database access classes
some mappers (I am not sure if I could use data mapper pattern or else? Is good idea?)
Bussiness Tier (project type => class library)
entities which wil lbe mapped in data mapper in Data Tier
and some application logic
service tier (I am not sure if it should be individual tier, or subtier of bussiness tier - I want to use WCF)
Client (project type => WebForms / Android / WPF / ....)
will be communicate with bussiness tier over WCF
Is my idea good? I will be gratefull for any explanation or hint how patterns could I use with respect my low knowledge. I have requirements to use 2-3 patterns, becouse is school project. Thanks for answers
A implementation I have found quite useful is:
Data Access Layer:
Entity Framework: Unit of Work
Repository Pattern
Business Layer
This layer maps entities and db calls to DTOs
Presentation Layer
Here you present your DTOS using MV? or any other model
There you are using at least 4 design patterns.
For the data layer I would go with repository pattern and unit of work pattern. This is really good way to abstract data layer and create testable code which can be easily unit tested.
Business layer it depends, by DDD business should be encapsulated inside rich data model. Anemic data model is considered as anti pattern. But personally rich model can lead to the ruin of the separation of concern paradigm. Sometimes it is useful to have anemic data model and business layer on top of that model. Like handlers where every handler does exactly one action...
On top of business layer is usually application layer which expose interface to the outside, to your clients. It should be really thin without any business logic in it. Maybe Restful API which will enable you to connect various clients like Android, wpf, Javascript...

Patterns of Enterprise Application Architecture - consolidating business data

To give you a quick overview of my application architecture, I have the following layers in my application:
Domain Model - Models the problem domain and business rules.
Service Model - Models the service contract consumed by the application.
Data Access Layer - Persistence of domain models, in this case using EF.
Services - Implementations of the service model.
Website - MVC web application.
Web API - RESTful web service API.
Now the problem is that the Web API came later; the MVC web application was the first thing that was built on top of the architecture.
I find myself having to replicate business logic and ViewModels (MVC) and Messages (Web API)...According to the DRY principle, I shouldn't be doing this, so the natural solution is to push the business logic into its own layer which is independent of the application layers.
But...this means that the business logic layer needs it's own set of models which sit between the application layer and the business logic layer. In this respect, it would not be applicable to use domain models, since these really shouldn't ever hit the application layer.
So in short, I'm looking for an industry accepted standard for business logic modelling. Is there an accepted standard for how this should work, and if so, what type of model (i.e. it's not a domain model, and it's not a view model) belongs to the business logic layer?
You have stumbled upon a contested point of discussion. I myself have struggled with this for a long time.
Object bigots will argue that you shouldn't even have a service layer. Your domain model could then be directly consumed which would eliminate the duplication of logic. Granted, those were the good old days of software modeling. With the advent of the web, apis and SOAs, we are forced to look at alternative ways of modeling our software. Enter Anemic Domain models.
Anemic Domain models essentially consist of light weight objects that resemble DTOs more than anything, with underlying services that do the heavy lifting.
The architecture you have described above seems to be a hybrid design. I am guessing by now you must have run into the issue of mapping EF classes to domain objects, which creates yet another layer of objects, unless you use POCOs, in which case you run into namespace issues and what not.
Anyways, I don't think there is an industry standard. What I can tell you is that I have seen a few patterns emerge here and there leaning towards Anemic Domain Models and it's not hard to see why. In disconnected environments (e.g. web, API), complex objects don't work very well, hence the affluence of services.
Since you have layered your application nicely and do not wish to expose your domain model objects, I would suggest using Anemic Models in your service implementations. These would essentially function as DTO objects that can be reused and serialized if the need be, but can also implement basic logic that may even map back to functionality implemented in the services.
On a final note, there is no one-size-fits-all. Use the right tool for the job. Patterns are meant to be guidelines, not step-by-step instructions, so make sure you feel free to tweak them in order to fit your particular needs while retaining the general idea.
You can read more about Anemic Domain Models here:
https://en.wikipedia.org/wiki/Anemic_domain_model
Make sure to check out Martin Fowler's objections to Anemic Domain Models as well:
http://www.martinfowler.com/bliki/AnemicDomainModel.html

Do I need WCF layer in the backend layer of my WPF application?

I am creating my first stand alone desktop WPF application using Entity Framework. Do I need a WCF layer to access database? Is this a bad practise if I just call DBContext directly from ViewModels?
TL; DR
The short answer is: it depends!
The long answer
It depends on your use case you need to implement. If you need to add another layer of abstraction -the WCF layer- to hide your OR/M away you can do it. However if your strategy is easy enough like a standalone WPF application I wouldn't bother making a WCF layer. You can simply access the IDBContext in your application, but keep in mind to not tightly couple your viewmodels with EF.
Always worth try keeping the concerns separate!
And these concerns are:
Data- or Persistence (EF) Models that are used to map your database to your OO models
ViewModels that are supporting your Views with data to show
Mapping of your Persistence and ViewModels
This way you can achieve a lightweight setup that aims for better separation and better testing ability.
Further Extensibility
Later on your development path, when you arrive at a point where you need to add an infrastructural concern like a WCF layer which could serve as a public API -or an entry point- to your shared database access, you can easily add it as a new project, put its classes behind interfaces (these are the only ones you will have as reference added to your WPF project) and let this project have the exact implementations.

N-Tier Application Design

I am fairly new to Arhitecture Designs in OOP ( I'm coming from programming robotics, so it's a bit of a struggle ). The team that I am taking part of is creating a rather large application and the Leading Project Manager presented us with the requirements and in that requirements we must use Layers in creating the modules. The technologies we are using are C# WinForms and Oracle for the data-store.
My module consists of User Administration and I have tried to separate the logic from the implementation, so I have the following arhitecture:
Business Layer
Data Layer
Presentation Layer
I am using the Repository Pattern and IoC with EF and everything looks and works fine but now my boss has told me that I need to seperate the Presentation Layer from the Data Layer completely. The problem consists that from the Presentation Layer I use IoC and if I want to create a User object for example I do the following:
_userRepo.InsertNewUser(new User { props here } ); .
So this is incorrect because I access the DAL directly. My boss has told me that I need another layer that isolates these kind of calls and implement Business Rules ( ?! )
I have searched and researched the internet and I found nothing of help ( mainly because everything is filtered here at work ).
I think my boss wants something of a Domain Layer / Service Layer but I have no ideea how to implement it in the current design. I can post the project without any problem, any sensitive data will be removed from the code.
Any help would be appreciated.
I'm posting this as an answer, even though it might be opinion-based, and even though I cannot read your boss's mind :-)
Fundamentally, I think what your boss wants is to reduce dependencies between all layers. The architectural pattern you choose to do this, depends on the application at hand. What you described looks like a three-tier architecture. Let us briefly recall how a three-tier architecture looks like, and how things are supposed to work:
The presentation tier displays information and serves as a boundary to the user.
The application tier (or business logic) controls the functionality of the application. In particular it processes data and distributes it to the other tiers.
The data tier, containing the data access layer (DAL), stores or retrieves data. It should keep your application independent from the storage solution at hand. It will usually work with data access objects (DAOs).
There are different schools of thought when it comes to which tier should know which other tiers. But from what I read, I think you are supposed to promote the business logic as kind of mediator. This means, the business logic knows the presentation tier and the data tier, but the other tiers do not know each other. I try to clarify this by going through two sample scenarios:
A. Display an existing user
Business logic asks data tier for a specific User DAO, e.g. the one corresponding to id==123.
Data tier returns the User object.
Business logic reads the values stored in the User object and sets the values in the presentation tier accordingly, e.g. the firstName, lastName etc. It does not forward the User itself, only the contained values.
B. Create a new user
Presentation tier collects all values necessary to create the new user.
When "submitting", these values arrive in the business logic (e.g. IoC).
The business logic tells the data tier to create a new User object with the values it got from the presentation tier.
The data tier creates and stores the object.
What creates dependencies between the different tiers are the DAOs. I.e. if your presentation tier was to instantiate a User object, it would need to import a class belonging to the DAL (which is not what your boss wants).
So what you can do instead is to leave all the communication between presentation tier and data tier to the business logic.
As an alternative in scenario B, you can also make the business logic create the User, so that your DAL methods get simpler.
As I said in the beginning, there is no one way of doing it. If you need more specific information or have further questions, don't hesitate to ask.
Thank you for the all the answers and guidelines so far.
I think what my boss wants ( I didn't get reach of him because he is in DE and I am in RO ) is to fully separate the concerns between layers, something like the Model-View-Presentation Pattern, so that the Presentation Layer ( UI ) will not directly access the Data Layer. It can access it but through an intermediary layer.
I added a Domain/Service Layer to the application and now the Presentation Layer calls the Service Layer and the Service Layer calls the Business Layer and creates the user / group objects.
The following thing is, he said something about Business Rules that this Domain Layer should include. What are these Business Rules, an example would be appreciated?
The only think I came up for Business Rules were some Validation Rules, suchs as: Before you call: return userRepository.GetUserName( User user ) check the User object passed as a parameter that is not null, or similar checks.
So now the "mechanics" are:
In the Presentation Layer I inject into the constructor the IService object and then I use the IService object to call a method for example "GetAllUsers()".
The IService per-se is in fact a "copy" of the User Object's Repository class so when the IService object calls "GetAllUsers()", there is a exact named method in the IService classes that will do: "return _userRepository.GetAllUsers()" - in this way the Presentation Layer calls object specific methods through an Intermediary Layer and this Intermediary Layer will have direct access to certain methods of the DL.
I hope I made my self as clearly as possible. I will provide screenshots if necessary.
As I stated before, I'm just beggining to have experience with Arhitecture Design, since in the robotic fields there is no such thing, so please do not throw so many rocks :D

Using MVC + Repository Pattern, where Business Logic should be?

I want to know the right concept about it. If I have a MVC application with Repository Pattern, where the BL should be?
Should it be inside the Model? Model should have all the business
logic before call the unitofwork to insert or not the data into
database?
Should it be in the controller? Before call the model?
Should I have a service layer to do the business logic and decide if
I should call the Model to call the UnitOfWork to save the data?
A good explanation will help a lot too.
The short answer - it depends. If it's a fairly complex or sizable application, I like to create a service layer project with the repositories as dependencies. If it's a small application, I'll put the logic in the controller. In my opinion, if it takes more time and effort to create the service layer than it would be to create the application (i.e. one or two controllers), then it doesn't make sense to me to go that route. You also need to consider the likelihood that the application will grow. What might start small could grow into something much bigger and in that case, again, it might be more beneficial to create the separate service layer.
The third one... and then some.
Your application structure could look like this (each in different projects):
Data storage layer (e.g. SQL database)
ORM (e.g. NHibernate or Entity Framework)
Domain (including abstract repositories and entities)
Service layer (and optionally business)
MVC application (which has it's own models relating to the entities)
but there are many ways to go about this depending on the complexity and size of your application.
There is no "correct" answer to this question, it is primarily opinion-based. You can read about my opinion in the following project wiki:
https://github.com/danludwig/tripod/wiki/Why-Tripod%3F
https://github.com/danludwig/tripod/wiki/Dependency-and-Control-Inversion
https://github.com/danludwig/tripod/wiki/Tripod-101
https://github.com/danludwig/tripod/wiki/Testing,-Testing,-1-2-3
https://github.com/danludwig/tripod/wiki/Command-Query-Responsibility-Segregation-(CQRS)
Another piece of advice I would like to offer is never put any business logic in viewmodels or entities. These classes should not have methods, only properties to contain data. Separate your data from behavior. Use models for data, and other types for behavior (methods).

Categories