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

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?

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.

Related

Should I create namespaces for Entities and Value Objects?

I am building an application using DDD principles. I am now thinking about the namespace structure in the core of my application. Please see the idea below:
Company.Application.Core.Entities
Company.Application.Core.ValueObjects
However, I cannot find a single example of an application on GitHb, which follows this convention. Is there a specific reason not to follow this naming convention?
I also have a base class for entities i.e. Company.Application.Core.Entities.Entity and a base class for value objects i.e. Company.Application.Core.ValueObjects.ValueObject
The alternative option is to put all Value Objects and Entities in: Company.Application.Core
Your approach will work, but such composition tells story about your code focused on DDD Building Blocks, not about immanent features of your domain. In DDD we want to show important things about domain, the technology issues are not the most important concerns anymore.
I suggest creating following namespaces:
YourCompany.YourApplicationName.YourParticularBoundedContextName.Application
here you can keep all Application Scope building blocks i.e. Application Services and DTO's which are used to transfer parameters to Application Services and return data from them.
YourCompany.YourApplicationName.YourParticularBoundedContextName.Domain
this is the namespace where you will create subnamespaces for Domain Scope building blocks.
YourCompany.YourApplicationName.YourParticularBoundedContextName.Domain.AggregateName
each Aggregate have its own namespace in which there are Aggregate Root class, Entities and VOs used internally in this Aggregate, Repository interface, Aggregate Factory if needed etc.
I don't know if in C# it is possible, but in Java there is another advantage of having separate package (namespace) for Aggregate - you can make Aggregate Root class public and all other Entities and VOs that are internally used as package scope, so they will not be visible outside package (namespace). This way you build public API for your Aggregate that no one can break, because there is a guardian: the compiler :)
YourCompany.YourApplicationName.YourParticularBoundedContextName.Infrastructure
here is a place for repositories' implementations (each in subnamespace of corresponding Aggregate)
Base classes can be kept in:
YourCompany.YourApplicationName.Domain
and even kept in separate project as you can try to reuse it in another application.
What is the advantage? When working with code you are focusing on features and domain rather than on technological aspects. You will more frequently have to cope with problems like "how does this process flow look like" than "I want to see all my Entities and VOs at once", so let your code structure support this. Separating Entities (Aggregates parts actually) and VOs (also Aggregate parts) into separate namespaces you lost information what is working with what. You can simple end with big ball of mud, because you will reuse something that shouldn't be reused.
Please look at:
https://github.com/BottegaIT/ddd-leaven-v2
it is a sample project in Java with packaging done this way. Maybe it will help you.
Another example is:
https://github.com/VaughnVernon/IDDD_Samples
which is a sample for Vaughn Vernon's book about DDD.
There is also article that can be useful:
http://www.codingthearchitecture.com/2015/03/08/package_by_component_and_architecturally_aligned_testing.html
Using separate namespaces for your Entity types (that map to database tables etc.) and your DTO types (used for passing data between client and server layers of your application) is pretty standard practice, even if .Entities and .ValueObjects aren't particularly common choices. I don't think it's worth worrying about too much as long as you use them consistently.

Is there a benefit in using the repository pattern to simplify the controller?

I have created quite a few projects where my business logic has been directly accessing my data layer. Since its the only way I have been setting up my MVC projects, I cannot say for sure where the system has been lacking.
I would, however, like to improve on this. To remove many return functions from my controllers, there are 2 ways I see to achieve the same goal.
Including these return functions as methods of the model classes(doesnt make sense, since the datacontext would need to be initialized within every model).
Using a repository
After reading up a bit on repositories, I haven't come across any instances where "Thinning your controllers" may be a 'pro' to using a repository(a generic repository, could be related to this).
For an understanding of the answer I am looking for, I would like to know if, besides the above mentioned reason, I should use a repository. Is there really a need for a repository?In this case, my project will only be reading data (Full CRUD functionality wont be needed).
There is definitely a need for a repository. Every class should only have one real responsibility where possible; your controller's job is simply to 'give' information to the view. An additional benefit to this is if that if you do create a repository layer then, providing you make interfaces for them, you can make your solution a lot more testable. If your controller knows how to get data from a database (past using a repository - or similar) then your controller is "doing" more than one thing, which violates the single responsibility principle.
I used to use a generic repository pattern using the library SharpRepository, however I found that I needed more fine-grained control over what each of my repositories had access to (for example, there were some repositories I did not want to have mutation control and only be read-only). As a result I switched back to using non-generic repositories. Any half-decent IOC tool will be able to register your repositories based on convention (i.e, IFooRepository maps to FooRepository), so the number of classes is not really a factor.
As a commentor mentioned your title doesn't really sum up your question, so I'll summarize it for other answer authors:
Is there a benefit in using the repository pattern to simplify the controller?

What pattern is layered architecture in asp.net?

I am a asp.net developer and don't know much about patterns and architecture. I will very thankful if you can please guide me here.
In my web applications I use 4 layers.
Web site project (having web forms + code behind cs files, user controls + code behind cs files, master pages + code behind cs files)
CustomTypesLayer a class library (having custom types, enumerations, DTOs, constructors, get, set and validations)
BusinessLogicLayer a class library (having all business logic, rules and all calls to DAL functions)
DataAccessLayer a class library( having just classes communicating to database.)
-My user interface just calls BusinessLogicLayer. BusinessLogicLayer do proecessign in it self and for data it calls DataAccessLayer functions.
-Web forms do not calls directly DAL.
-CustomTypesLayer is shared by all layers.
Please guide me is this approach a pattern ? I though it may be MVC or MVP but pages have there code behind files as well which are confusing me.
If it is no pattern is it near to some pattern ?
That's not four layers, that's three layers, so it's a regular three tier architecture.
The CustomTypesLayer is not a layer at all. If it was, the user interface would only use the custom types layer and never talk to the business layer directly, and the data access layer would never use the custom types layer.
The three tier architecture is a Multitier architecture
As far as patterns go, I recommend getting to grips with these:
My biggets favourite by a mile is the Dependency Inversion Principle (DIP), also commonly known as (or at least very similar to) Inversion of control (IoC) ans Dependencey Injection; they are quite popular so you should have no problem finding out more info - getting examples. It's really good for abstracting out data access implementations behind interfaces.
Lazy Load is also useful. Interestingly, sometimes you actually might want to do the opposite - get all the data you need in one big bang.
Factory pattern is a very well known one - for good reason.
Facade pattern has also helped me keep out of trouble.
Wikipedia has a pretty good list of Software design patterns, assuming you haven't seen it yet.
A final thing to keep in mind is that there are three basic types of patterns (plus a fourth category for multi-threaded / concurrency); it can help just to know about these categories and to bear them in mind when you're doing something of that nature, they are:
Creational
Structural
Behavioral
Take a look at the Entity Framework or LinqToSQL. They can both generate your data access layer automatically from your database. This will save you a lot of (boring) work and allow you to concentrate on the interesting layers.
Code-behind does not really have anything to do with architecture - it is more of a coding style. It is a way of separating logic from presentation. Any architecture you mention can be used with or without code-behind.
You seem to be describing a standard three-tier architecture. MVC is a pattern than describes how your layers and the user interact. The user requests a page (represented by a View), which requests its data from the Controller. The Controller communicates with your business layer (Model) to extract the correct data and passes it to your View for display. If the View is interactive, for instance it allows the user to update something, then this user action action is passed back to your Controller, which would call the relevant method against the business layer to save the update to the database.
Hope this helps.

ASP.NET MVC: What's the difference in concept between Service and Repository

The question I'm asking is kind of subjective. I've seen twice, while exercising with real projects such as StoreFront, both Repository and Services. Sometimes they can just be folders or projects attached to the solution. But they contain classes and interfaces.
So, I'd like to know what goes to the repository and what goes to the services. So far, I was familiar with repositories (we put methods and properties in the repository to reduce the complexity in the controller). How about the services?
So, ASP.NET MVC: What's the difference in concept between Service and Repository? (Maybe none)
My question is Kind of subjective, but I'd like to make sure that I'm not missing anything.
Thanks for helping
Generally, the repository simply provides an interface to data. There is no application logic there. Services provide interfaces to application logic. Services often use repositories.

oo question - mixing controller logic and business logic

I'm not sure if I'm using "standard" terms, but this is a basic OO question I'm trying to resolve.
I'm coding a windows form. I don't want logic in the form event handler, so I just make a call to a custom object from there.
At the custom object, there are two sets of logic.
The "controller" logic, which decides what needs to get done and when.
The actual business logic that does what needs to be done (for example a control that performs a math operation and returns results, etc.).
My question is, does OO architecture allow for having both of these in a single object? Or is it recommended to split them out into a "controller" object and a "business logic" object? Is there a design pattern I should refer to for this?
For the time being, I've started down the route of combining them into one object. This object has a "start" method which contains the controller logic. This method then calls other methods of the object as needed, and ultimately returns results to the caller of the object.
What you're doing is a form of "fat controller" architecture. These days software development is trending toward thin controllers.
OO design is all about decoupling. If you internalize only one thing about OO programming, let it be that.
Check out "Domain-Driven Design Quickly." This free e-book is a condensed introduction to the concepts covered in Eric Evans' important book "Domain-Driven Design."
Getting educated in these concepts should help you to understand how to separate business logic from the controller, or service layer.
In general, you should probably have these in two different objects, but there's a qualifier on that. It may make sense, if your project is small enough and your object model is not complex enough, to have the functionality composed into one object; however, if your functionality is complex enough, it's almost certainly going to be better for you to segregate the controller and the business objects. At the very least, design the system with an eye towards separating the controller and the business objects at a later point, if you don't completely separate them now.
No, I don't put business logic in controllers. I add an intermediate service layer that's injected into controllers. Let the service do the work. Controllers are for routing requests and marshaling responses.
Putting the logic in a clean service layer is "service oriented", even if you aren't using web services or WSDL. It has the added benefit of still working if you decide to change controller/view technologies.
The answer to you design question can is as the following scenario: how would you design your application if you also had to provide a web-client for it.
Both your Windows Forms UI and you Web UI would be calling the same classes and methods. The only difference, then, would be how each populates the UI and communicates with the other layers.

Categories

Resources