{"id":506,"date":"2023-08-02T21:12:17","date_gmt":"2023-08-02T21:12:17","guid":{"rendered":"https:\/\/anwarshoukryclinics.com\/?p=506"},"modified":"2024-02-01T15:05:48","modified_gmt":"2024-02-01T15:05:48","slug":"the-method-to-build-microservices-with-onion","status":"publish","type":"post","link":"https:\/\/anwarshoukryclinics.com\/index.php\/2023\/08\/02\/the-method-to-build-microservices-with-onion\/","title":{"rendered":"The Method To Build Microservices With Onion Structure: Hands-on Experience"},"content":{"rendered":"<p>The deeper the layer resides inside the Onion, the less dependencies it has. Testability is very high with the Onion structure as a outcome of every thing depends on abstractions. The abstractions can be simply mocked with a mocking library corresponding to Moq. To study more about unit testing your initiatives in ASP.NET Core try this text Testing MVC Controllers in ASP.NET Core. The Onion architecture is a form of layered architecture and we will visualize these layers as concentric circles. The Onion architecture was first introduced by Jeffrey Palermo, to beat the problems of the traditional N-layered structure approach.<\/p>\n<p><img decoding=\"async\" class='aligncenter' style='display: block;margin-left:auto;margin-right:auto;' src=\"https:\/\/globalcloudteam.com\/wp-content\/uploads\/2022\/08\/what-qa-testing-768x512.jpg\" width=\"301px\" alt=\"onion software architecture\"\/><\/p>\n<p>The apparent advantage of the Onion structure is that our controller\u2019s strategies turn into very skinny. We moved all the important business logic into the Service layer. As we are in a position to see, it consists of the Web project, which is our ASP.NET Core application, and 6 class libraries. The Domain project will hold the Domain layer implementation. The Services and Services.Abstractions are going to be our Service layer implementation. The Persistence project will be our Infrastructure layer, and the Presentation project would be the Presentation layer implementation.<\/p>\n<p>All of the layers interact with one another strictly by way of the interfaces outlined in the layers under. The flow of dependencies is in the direction of the core of the Onion. We will clarify why that is important in the next section. An efficient design pattern for writers of clean, long-lasting code is onion structure. The Onion Architecture helps to ensure that every layer has a distinct responsibility and is isolated from the other layers by grouping concerns into various layers. The adaptable Onion Architecture enables builders to change an utility without affecting different system components.<\/p>\n<p>One of the key variations between Onion Architecture and Clean Architecture is how they approach the dependency administration downside. If you have comparatively mounted queries that won\u2019t change easily, this structure would work very well. Using IQueryable will velocity up your preliminary growth cycle. Because you by no means knew during which layer your query is contained. Good coding, clear approach and splitting of obligations. In my opinion, implementing one thing like this on the client aspect is overkill.<\/p>\n<h2>Service Layer<\/h2>\n<p>Also, the code is simpler to check due to dependency injection, which also contributes to making the software program extra maintainable. The application\u2019s entrypoint (usually, the main) must be responsible for instantiating all necessary dependencies and injecting them into your code. The inside layers shouldn\u2019t know in case your software is being uncovered via an API, by way of a CLI, or whatever. One of the core concepts in DDD is the Domain Model.A Domain Model is an entity that includes habits and information from some business mannequin. With n FKs, I would want n queries, plus the computational overhead to piece every little thing together the way I want the DTO to appear to be. In EF however, I can do a single query that may do all of that without delay.<\/p>\n<p>The outer layers of the structure implement these interfaces. This implies that in the Domain layer, we are not concerning ourselves with infrastructure particulars such as the database or external companies. Yes, present projects can be migrated to onion architecture, however the process requires cautious planning and execution.<\/p>\n<p>There is now not a Startup.cs file generated since .NET 6.zero. Remember that we now have two summary exception courses BadRequestException and NotFoundException inside of the Domain layer? Do you keep in mind how we break up the Service layer into the Services.Abstractions and Services projects? The Onion structure can also be commonly often recognized as the \u201cClean architecture\u201d or \u201cPorts and adapters\u201d.<\/p>\n<h2>What Are Some Issues With Onion Architecture?<\/h2>\n<p>We may create an initialization script, connect to the Docker container while it is working the database server, and execute the script. Notice that we create a swap expression around the exception instance and then perform a pattern matching based <a href=\"https:\/\/www.globalcloudteam.com\/onion-architecture-in-development\/\">onion architecture<\/a> on the exception type. Then, we are modifying the response HTTP status code depending on what the specific exception kind is. By now it must be obvious that the Presentation project will only have a reference to the Services.Abstraction project.<\/p>\n<p>By doing this, your Infrastructure code can anticipate to obtain an object that implements an interface, and the principle can create the shoppers and cross them to the infrastructure. So, when you should take a look at your infrastructure code, you might make a mock that implements the interface (libs like Python\u2019s MagicMock and Go\u2019s gomock are excellent for this). It\u2019s responsible for dealing with the persistence (such as a database), and acts like a in-memory collection of area objects. The Infrastructure Layer is the outermost layer of the Onion Architecture.<\/p>\n<p>To be honest, I didn\u2019t use Razor Pages a lot, virtually none, so I am really undecided the method to do it there. Probably there&#8217;s a means, but as I didn\u2019t do it personally, I can\u2019t provide an answer to your query. Instead of in reminiscence, I shall be using a database \u2013 Adventureworks 2017. But how are we going to use the controller if it is not within the Web application? Great, we now have seen tips on how to implement the Presentation layer.<\/p>\n<ul>\n<li>This is the outermost layer (together with Infrastructure) and it&#8217;s the window of the exterior shoppers to your application.<\/li>\n<li>If you check with ForCreation and ForUpdate DTOs, then these are validated with the attributes because we use them inside the request in our actions.<\/li>\n<li>The utility layer stands between the area layer and the infrastructure layer.<\/li>\n<li>\u2013 the REST service shouldn\u2019t return all database information without delay.<\/li>\n<li>The actual kind of database and the means in which of storing information is set at the upper infrastructure level.<\/li>\n<\/ul>\n<p>Developers can substitute or update elements with out having to vary other system elements since every layer is autonomous and only communicates with different levels by way of properly defined interfaces. The modular format favored by Onion Architecture makes it easy to scale the application. The design is constructed around a core domain layer that homes the application\u2019s enterprise logic and is encircled by other layers that cope with varied elements of the appliance.<\/p>\n<h2>Cumbersome Whenever You Don\u2019t Have Many Business Guidelines<\/h2>\n<p>I hope you\u2019ll find my expertise useful for your tasks. But it doesn&#8217;t quite solve the validation drawback, particularly if you have to take information from a database or from one other microservice. Therefore, we built a validation mechanism into the MediatR pipeline utilizing Fluent Validation. CQRS is a development principle claiming that a method must be both a command that performs an motion or a request that returns information. At occasions, we had to move a selected performance into a separate microservice if it appeared in many places in the system. On the contrary, if some functionalities were tightly connected, we had to combine microservices into one.<\/p>\n<p><img decoding=\"async\" class='aligncenter' style='display: block;margin-left:auto;margin-right:auto;' src=\"https:\/\/globalcloudteam.com\/wp-content\/uploads\/2020\/10\/6a8cb57c-97a2-4652-a52b-8d959bd68286sizelarge-768x458.jpg\" width=\"301px\" alt=\"onion software architecture\"\/><\/p>\n<p>Clean Architecture is a software program design sample launched by Robert C. Martin(Uncle Bob) in 2012 within the publish. The architecture emphasizes the separation of concerns, with each circle liable for a distinct set of duties. The architecture  places a particular emphasis on the use of interfaces to decouple components. In common, the deeper we dive, the closer we get to the area and business rules. The outer circles represent mechanisms and the internal circles symbolize core domain logic.<\/p>\n<p>Any developer, conversant in the area, ought to be succesful of perceive the code, and simply know where to change things.Modifying the view layer mustn&#8217;t break any domain logic. Modifying the database modeling mustn&#8217;t have an effect on the software\u2019s business rules. You ought to have the power to simply take a look at your domain logic.Then, we should start excited about separating different issues into different units of code. You don\u2019t modify the entity mannequin, it must be the illustration of your database desk. What you do is creating a brand new DTO which inserts your wants and use the service layer to do some enterprise logic to populate that DTO and return it in consequence to the controller and to the client.<\/p>\n<div style='text-align:center'><iframe width='565' height='314' src='https:\/\/www.youtube.com\/embed\/wkfgJgs0Q1k' frameborder='0' alt='onion software architecture' allowfullscreen><\/iframe><\/div>\n<p>If you employ mappings in both the principle project and the service layer, then having it in the main initiatives is a greater possibility. In the Services.Abstractions project you can find the definitions for the service interfaces which are going to encapsulate the principle business logic. Also, we&#8217;re using the Contracts project to outline the Data Transfer Objects (DTO) that we&#8217;re going to devour with the service interfaces.<\/p>\n<p>You will see the the Domain Model\/Core layer is referenced across a quantity of layers, and that\u2019s nice, to a sure diploma. We are additionally in a position to write Unit Tests for our business logic while not coupling our tests to implementation both. In my implementation, I intend to show a few of the key layers of this architecture and the way they work together. See example repository here <a href=\"https:\/\/www.globalcloudteam.com\/\">https:\/\/www.globalcloudteam.com\/<\/a>.Note \u2014 The following is my interpretation of this Architecture Pattern and will not be as intended by it\u2019s publishers. Recently I\u2019ve seen there&#8217;s plenty of error-prone demos and videos the place individuals report about onion, however it could have a lot of violations \ud83d\ude42 The idea with break up of service layer \u2013 makes great sense.<\/p>\n<p>In the Application layer, the FareRepository is ready to retrieve knowledge from external sources and rework it into meaningful Business Entities. The very centre of the Model, this layer can have dependencies only on itself. It represents the Entities of the Business and the Behaviour of those Entities. Business Logic behaviour is declared as contracts with the usage of interfaces in a Object-Oriented context. Code should depend only on the same layer or layers more central to itself.<\/p>\n<p>It consists of algorithms which are important to its purpose and implement the use cases which may be the heart of the application. This anti sample has plenty of problems that are nicely described in Fowler\u2019s article. It just incorporates data, and is used solely on this use case as a return value. As this layer is solely logical, it ought to be fairly straightforward to check it, as you don\u2019t have to worry about mocking IO operations. The area layer is the innermost layer of the structure.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The deeper the layer resides inside the Onion, the less dependencies it has. Testability is very high with the Onion structure as a outcome of every thing depends on abstractions. The abstractions can be simply mocked with a mocking library corresponding to Moq. To study more about unit testing your initiatives in ASP.NET Core try [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[53],"tags":[],"_links":{"self":[{"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/posts\/506"}],"collection":[{"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/comments?post=506"}],"version-history":[{"count":1,"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/posts\/506\/revisions"}],"predecessor-version":[{"id":507,"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/posts\/506\/revisions\/507"}],"wp:attachment":[{"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/media?parent=506"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/categories?post=506"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/anwarshoukryclinics.com\/index.php\/wp-json\/wp\/v2\/tags?post=506"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}