Search code examples
c#mediatoronion-architecture

How to reuse validation code in multiple features? - Onion architecture


From what I understand in onion architecture, the domain must contain all the business logic. And enforcing database validations are typically done by using Services.

My code is inspired from this repo https://github.com/asadsahi/AspNetCoreSpa , where they are using features, where each folder has all the validation rules and logic for specific feature inside the application layer.

What is the best way to share a specific validation for multiple features? Should I create a service and use it for each feature?

And what is the reason that they moved all the business logic to the application layer while the domain entities does not have any logic?


Solution

  • I found a good article talking about what I need here Dealing with Duplication in MediatR Handlers

    Excluding sub-handlers or delegating handlers, where should my logic go? Several options are now available to me:

    Its own class (named appropriately) Domain service (as was its original purpose in the DDD book) Base handler class Extension method Method on my DbContext Method on my aggregate root/entity As to which one is most appropriate, it naturally depends on what the duplicated code is actually doing. Common query? Method on the DbContext or an extension method to IQueryable or DbSet. Domain behavior? Method on your domain model or perhaps a domain service. There’s a lot of options here, it really just depends on what’s duplicated and where those duplications lie. If the duplication is within a feature folder, a base handler class for that feature folder would be a good idea.

    In the end, I don’t really prefer any approach to the another. There are tradeoffs with any approach, and I try as much as possible to let the nature of the duplication to guide me to the correct solution.