In Clean Architecture with CQRS pattern, should a type used only in a command go in the Application or in the Entities layer? - cqrs

In Clean Architecture applied to an API with CQRS pattern, if I have a command in the Application layer for modeling the post payload of an endpoint and that command has a property of type X that is only used in that command: should that type X go in the Entities layer or in the same Application layer?

According to clean architecture the entities layer only contains "cross enterprise logic". So if your type X is only used by this command, this type should be on the application layer as well.

Related

DDD, CQRS, onion architecture, ef core for enterprise level app

Recently I have found that following approach works great for many projects that I have worked on.
The issue however is, that I read that ef core DbContext is a UoW by itself, and I should NOT create my own UoW and repositories. But in such case, I am unable to abstract my persistance layer from my application logic layer.
TL;DR question is:
Is it possible to NOT to have own repositories nor own UoW and still follow the mentioned architecture with DbContext as UoW?
My architecture is like follows:
Layer 1 (most inner):
Aggregates, Entities, POCO domain classes, Value Objects
Layer 2:
Domain services
Layer 3:
Application services (CQRS commands, queries, handlers) and Repository Interfaces
Layer 4A: (persistance layer)
Repositories implementation (DbContext injected here)
EF Core mappings (ORM mappings)
Layer 4B:
Asp MVC API (DI registered here)
Controllers of API just issues commands and queries (via MediatR).
The advantage of above approach is that the app core (layers 1, 2 and 3) are completely abstracted from persistance.
The disadvantage is that you really have to write your own Repositories.
Is it correct approach? Or am I missing something?
Why is a DbContext is a unit of work?
The DbContext captures all changes that you are making within one single transaction via one single commit (SaveChanges).
Why shouldn't you create your own?
Ideally, you should only be committing to one single data store via one single transaction. If you are either saving to multiple data stores in multiple transactions or saving to the same data store in several transactions, then you face the likely possibility of data corruption. If you are using a distributed transaction across multiple data stores, well then God help you.
SaveChanges should therefore be sufficient, so why create your own?
But what about abstraction?
If SaveChanges is sufficient, then how do we abstract out our dependency on EF? You can introduce an IUnitOfWork interface with a single method, Commit, which you can implement by calling DbContext.SaveChanges.
And repositories?
I am not sure I understand not creating Repositories as a hard rule. As part of abstracting out your persistence layer, it is helpful to have a layer such as IRepository to provide that separation. That said, you should not be creating a repository per table. A repository per Aggregate is more appropriate. Each repository will load the entire Aggregate to ensure consistency within the boundary of the Aggregate.
...
In general, I would caution against following advice that speaks in absolutes if you don't understand the reasoning behind that advice. You should be able to formulate the same conclusion given the same starting information for yourself. Otherwise, you are just applying rote memorization to a pattern that does not always benefit from that approach.

Archimate - Application Layer - Interfaces + Database

I am quite new to the Achrimate 3.0 and I am trying to make my model in it. I put an example below. My goal is to model this stream of data where I have a Source System which is creating output files in specific format -> next Step is Pulling the data by processing component and looking for some values in connected DB -> final step is then deliver this data (pushed by processing component) to Target Systems.
Q1: What relationship is correct to Application Component and Interface? In the picture is triggering (but maybe FLOW fits better) ?
Q2: Database is joined via Access relationship ?
Q3: For my purposes it will need to hold information about DB (columns+types+notes) structure in the diagram, any tips, how to manage it in Archimate ?
Diagram Example Here:
First, it would be nice to read the specification (http://pubs.opengroup.org/architecture/archimate3-doc/chap09.html#_Toc489946063).
Are you sure that you use only application layer? If so, then the interface is not defined correctly, the interface that you specified is rather related to the technology layer.
So:
Wrong interface (IMHO). Figure 67: Application Layer Metamodel of spec show you how elements can be linked on this layer.
Database can be represent as component, not DataObject.
In my experience - no good way. Use the standard reverse engineering mechanism. Associate the resulting UML objects with the Archimate elements if you need it.

3-Tier Architecture MVC 4 Project

I am working on a Web Application using ASP.Net MVC 4 3-Tier Architecture and I am stuck at certain points. I know here exist similar threads but none were clear enough. I have already created the needed layers which are UI(MVC4 project), BLL- Business Logic Layer(library class), BOL- Business Object Layer(library class that contains ADO.net) and DAL- Data Access Layer (library class).
Layer dependencies are as follows:
UI depends on BOL and BLL
BLL depends on BOL and DAL
DAL depends on BOL
I want you to correct me if I am wrong in the following. The BOL is the master reference layer which exchanges raw dB records with DAL then sends them to BLL which is responsible for any logical computations then gets the updated records and sends them to the controller in the UI.
Knowing the above,
Where should we place the CRUD functions?
Where and why should we create a class for declaring (plus set and get) the useful database fields?
What exactly should we put in the ViewModel folder; in other words since we have already defined the variables in the previous step and in the Entity then does it add any value to keep the Model folder?
Thank you in advance.
Can't be unambiguously correct answers on these issues, so any answer should be evaluated simply as an opinion. Here are my answers:
Where should we place the CRUD functions? CRUD is a frequent pattern at different levels. Hi-level Repository provides similar methods, as a low-level Table Gateway.
Where and why should we create a class for declaring (plus set and get) the useful database fields? These classes are usually simple Data Transfer Objects (DTO) or slightly more complicated Active Records. In accordance with the Dependency Inversion Principle the interface for these classes should provide the Business Logic Layer, and implementation should provide the Data Access Layer. Since DTO is very simple classes, they can be provided "as is" without interface/implementation separation.
What exactly should we put in the ViewModel folder; in other words since we have already defined the variables in the previous step and in the Entity then does it add any value to keep the Model folder? In theory entities should be our models; but in practice it's often not the case. F.e. in ASP.NET MVC models should provide not only the value of drop-down field, but also all possible values; so it requires the separate model class.
The result may be that you have three or four very similar classes at different levels of the application. Of course, it's not very good, so Aspect Programming may be applied in this case.

Is it possible to do DDD and REST interface and language mapping?

REST has a uniform interface constraint which is the following in a very zipped opinion based format.
You have to use standards like HTTP, URI, MIME, etc...
You have to use hyperlinks.
You have to use RDF vocabs to annotate data and hyperlinks with semantics.
You do all of these to decouple the client from the implementation details of the service.
DDD with CQRS (or without it) is very similar as far as I understand.
By CQRS you define an interface to interact with the domain model. This interface consists of commands an queries classes.
By DDD you define domain events to decouple the domain model from the persistence details.
By DDD you have one ubiquitous language per bounded context which expresses the semantics.
You do all of these to completely decouple the domain model from the outside world.
Is it possible to map the REST uniform interface to the domain interface defined by commands and queries and domain events? (So the REST service code would be generated automatically.)
Is it possible to map the linked data semantics to the ubiquitous languages? (So you wouldn't need to define very similar terms, just find and reuse existing vocabs.)
Please add a very simple mapping example to your answer, why yes or why not!
I don't think this is possible. There is a term which I believe describes this problem, it is called ontology alignment.
In this case have have at least 3 ontologies:
the ubiquitous language (UL) of the domain model
the application specific vocab (ASO) of the REST service
the linked open data vocabs (LODO) which the application specific vocab uses
So we have at least 2 alignments:
the UL : ASO alignment
the ASO : LODO alignment
Our problem is related to the UL : ASO alignment, so let's talk about these ontologies.
The UL is object oriented, because we are talking about DDD and domain model. So most of the domain objects entities, value objects are real objects and not data structures. The non-object-oriented part of it are the DTOs like command+domainEvent, query+result and error on the interface of the domain model.
In contrast the ASO is strictly procedural, we manipulate the resources (data structures) using a set of standard methods (procedures) on them.
So from my aspect we are talking about 2 very different things and we got the following options:
make the ASO more object oriented -> RPC
make the UL less object oriented -> anaemic domain model
So from my point of view we can do the following things:
we can automatically map entities to resources and commands to operations by CRUD, for example the HydraBundle does this with active records (we can do just the same with DDD and without CQRS)
we can manually map commands to operations by a complex domain model
the operation POST transaction {...} can result a SendMoneyCommand{...}
the operation GET orders/123/total can result a OrderTotalQuery{...}
we cannot map entities to resources by a complex domain model, because we have to define new resources to describe a new service or a new entity method, for example
the operation POST transaction {...} can result account.sendMoney(anotherAccount, ...)
the operation GET orders/123/total can result in an SQL query on a read database without ever touching a single entity
I think it is not possible to do this kind of ontology alignment between DDD+CQRS and REST, but I am not an expert of this topic. What I think we can do is creating an application specific vocab with resource classes, properties and operations and map the operations to the commands/queries and the properties to the command/query properties.
You have posed some interesting questions here.
To start with I do not quite agree with
By DDD you define domain events to decouple the domain model from the
persistence details.
I think you might be confusing Event Sourcing ES with DDD, ES can be used with DDD but its very much optional in fact you should give it a lot of thought before choosing it as your persistence mechanism.
Now to the bulk of your question, of whether REST and DDD get along if yes how ?
My take on it, yes they do get along, however generally you do not want to expose your domain model via a REST interface, you want to build a abstraction over it and then expose that.
You can refer to this answer here, for a little more detail.
However i cannot recommend enough the Implementing Domain-Driven Design book, Chapter 14 Application deals with your concern to a fair degree.
I could not have explained it more thoroughly than the book and hence referring you there :)

Architecture Design - MVC, EF, Rep, UoW, WCF, DI

Architecture Design
Looking for some suggestions for a new architecture that I am putting together.
Tools to use:
MVC 4 (If you have an example for MVC 3 it would suffice)
Entity Framework 4.1 (EF)
Repository Pattern
Unit of Work
POCO’s (T4 auto generated)
WCF (For CRUD functions. Retrieve data using concrete service classes)
Dependency Injection (Ninject)
Mocking (Moq)
Any other good tools let me know.
Firm on using EF for ORM with NHibernate being a second go to if EF proves unworthy.
What I have done so far
1) Presentation Project (MVC4, DI For services, Service Channel setup, View Models) -> references Domain Project (2)
2) Domain Project (POCO Entities, Domain Objects, Service Interface) -> References Business Project (3)
3) Business Project (WCF Service, Concrete Service Classes, Unit of Work) -> References Data Project(4)
4) Data Project (EF, Context + .edmx, Repositories and their interfaces) -> Looks at database
Question 1: Is this a good project breakdown?
Question 2: Is this a good place to put any of the mentioned items in the parentheses?
Question 3: Is there anything that should be somewhere that I have entirely left out?
A few side notes:
We have large record sets that we retrieve that easily exceed 100,000 records. Rather than going through a WCF service we are just calling a concrete service class that will increase performance. We topped out the max message size plus it took twice as long to retrieve records through WCF.
Question 4: Is there a better method to go about doing this? Performance is key. Reusability is not
Domain objects have a single attribute which is whatever POCO that it corresponds to. Example: I have a domain object called “Order”. It has a single attribute of “OrderPOCO” which holds all of the attributes. The domain object then has validation methods and references the necessary CRUD functions.
Question 5: Where should complex validation such as “does this record already exist” be placed? Can it just be done in the service itself?
Question 6: Are Domain object even necessary? Most other examples don’t have domain models if they are using POCO’s from what I can tell. Just a little confused on the idea.
Sorry this is very long. Any answer will be greatly appreciated but a comprehensive answer will be exponentially more helpful. We can pick tools to do different things but making them work together correctly is the hard part.
Criticism welcome!
Thank you all
Question 1, 2 and 3:
I've often seen architecture layouts containing only three layers. But if you want to keep your Domain Project layer and Business Project layer seperated and decoupled, so you can change one without affecting the other you should of course keep them in seperate assemblies. However POCO entities, unit of work and concrete service implementations are often very closely related to the domain and to the business rules of your application, so you could consider merging these two layers into one assembly.
I would move the reposiroty interfaces up in the businnes layer, remove the reference from busines layer to data layer, and have the UI layer reference the data layer instead. The UI layer then constructor injects the concrete repostiories into the domain/business layer. This keeps your domain/business layer clean of references to the technology dependent data assembly.
Question 4:
If performance is important, I would just call the concrete service classes.
Question 5:
I'm not sure what you mean by "complex validation".
Question 6:
EF can auto-generate the POCOs for you and place them in another assembly than the .edmx. See this article. This way your POCOs only depend on the T4 template and are not hard coupled to the EF.