In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to use the Dotnet Onion Architecture". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use Dotnet onion architecture.
I. brief introduction of Onion Architecture
The onion structure is actually a little old. There will be relevant theories in about the second half of 2017. However, a large number of articles are based on theoretical discussions, and we will use a project to complete this architecture today.
The onion architecture, sometimes called a neat architecture, is itself intended for high-quality software.
Compared with other architectures, the onion architecture is more testable, practical and stable, and is flexible enough to fully adapt to the possible growth and evolution of the project in the future. It can be said that the onion architecture perfectly solves the difficulties and problems faced by the three-tier or N-tier architecture.
When the bull is over, let's take a look at a picture:
This picture fully explains why it is called the onion architecture.
But that's not the point. The most important thing about this architecture is the code dependency principle inside: from the outside to the inside, and only in this direction. The code in the inner ring should not know anything about the outer ring.
As you can see from the image above, the onion architecture also uses the concept of layers. However, it is different from the three-tier or N-tier we are used to. Let's take a look at each layer:
Data layer (Domain Layer)
It exists in the central part of the architecture and consists of all the entities of business data. In most cases, it is our data model. In the later practice code, I use EF (Entity Framework) to operate the database.
Storage Tier (Repository Layer)
The storage layer acts as a link between the service layer and the data model in the architecture, and in this layer the context of all database operations and application data is maintained. The common practice is the interface, which is used to describe the read and write operations involved in data access.
Service layer (Services Layer)
The service layer is used to realize the communication between the storage layer and the project, and at the same time, the business logic of the entity can be saved. At this layer, the service interface is separated from the implementation to achieve decoupling and focus separation.
User interface layer (UI Layer)
I can't explain this. The final external layer of the project. Note that this could be a website or it could be API. There is no need to worry about whether there is an actual interface. In our practice code, I used API.
II. Practice
Okay, now go straight to the code.
1. Create a project
There is no explanation for this, it's all a routine:
% dotnet new webapi-o demo-f netcoreapp3.1
I use Dotnet Core 3.1for this project. The framework is not important, basically any version can be used.
Set up the Swagger below
This is my habit, and this project is a WebApi, it is convenient to install a Swagger.
% dotnet add package swashbuckle.aspnetcore
The setting of Swagger is not the focus of this article. Skip it. Students who need it can look at the source code.
Next, we will build three directories in the project:
DomainLayer
RepositoryLayer
ServicesLayer
These three directories correspond to the three layers above. UI in this project is actually the controller Controller, which already exists.
The purpose of building these three directories is to place three layers of code. When you code later, you will see the relationship between these three layers. In addition, in practical application, these three layers can be separated into three class libraries, which will be clearer.
As I said earlier, I can use EF to operate the database. So, three more libraries need to be introduced here:
Dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.Relational dotnet add package Pomelo.EntityFrameworkCore.MySql
Note that Microsoft's EF framework does not provide access to MySQL, so it references a three-party library.
At this point, the preparation of the project is completed.
two。 Implement the data layer
In the DomainLayer directory, create a Models directory. Under the Models directory, create two classes:
BaseEntity.cs
Public class BaseEntity {public int Id {get; set;} public DateTime CreatedDate {get; set;} public DateTime ModifiedDate {get; set;} public bool IsActive {get; set;}}
Customer.cs
Public class Customer: BaseEntity {public string CustomerName {get; set;} public string PurchasesProduct {get; set;} public string PaymentType {get; set;}}
Two classes, Customer are derived from BaseEntity. There is no special meaning, but also a habit. Moreover, it is convenient to write from the back to the storage layer.
Later, we will use the data tables created by the Customer and BaseEntity entity classes. In order for you to understand, I will create a directory EntityMapper here and write a table structure mapping in the directory.
CustomerMap.cs
Public class CustomerMap: IEntityTypeConfiguration {public void Configure (EntityTypeBuilder builder) {builder.HasKey (x = > x.Id) .HasName ("pk_customerid"); builder.Property (x = > x.Id) .ValueGeneratedOnAdd () .HasColumnName ("id") .HasColumnType ("INT") Builder.Property (x = > x.CustomerName) .HasColumnName ("customer_name") .HasColumnType ("NVARCHAR (100)"); builder.Property (x = > x.PurchasesProduct) .HasColumnName ("purchased_product") .HasColumnType ("NVARCHAR (100)") .IsRequired () Builder.Property (x = > x.PaymentType) .HasColumnName ("payment_type") .HasColumnType ("NVARCHAR (50)") .IsRequired (); builder.Property (x = > x.CreatedDate) .HasColumnName ("created_date") .HasColumnType ("datetime") Builder.Property (x = > x.ModifiedDate) .HasColumnName ("modified_date") .HasColumnType ("datetime"); builder.Property (x = > x.IsActive) .HasColumnName ("is_active") .HasColumnType ("bit");}}
Alternatively, you can create your own table ef.Customer:
CREATE TABLE `Customer` (`id`int NOT NULL AUTO_INCREMENT, `created_ date` datetime DEFAULT NULL, `customer_ name` varchar (255th) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `is_ active` bit (1) DEFAULT NULL, `modified_ date`datetime DEFAULT NULL, `payment_ type` varchar (50) DEFAULT NULL, `purchased_ product` varchar (100) DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE) 3. Implement the storage layer
This layer is mainly used to operate the database.
First configure the database reference in Startup.cs:
Public class Startup {public void ConfigureServices (IServiceCollection services) {services.AddDbContextPool (options = > options.UseMySql ("server=192.168.0.241;user=root;password=xxxxxx;database=ef", new MySqlServerVersion (new Version (8,0,21)), mysqlOptions = > {mysqlOptions.CharSetBehavior (CharSetBehavior.NeverAppend)) });}}
If you are lazy here, the connection string will be written directly into the code. When formally working on a project, it is best to write it in the configuration file.
Create a DataContext in the RepositoryLayer directory, which is used to place instances of related database sessions and operations:
ApplicationDbContext.cs
Public partial class ApplicationDbContext: DbContext {public ApplicationDbContext (DbContextOptions options): base (options) {} protected override void OnModelCreating (ModelBuilder modelBuilder) {modelBuilder.ApplyConfiguration (new CustomerMap ()); base.OnModelCreating (modelBuilder);}}
Then create a directory RespositoryPattern, which is used to store the classes for database operations. According to the principle of injection, there will be two files, an interface definition and an implementation class:
IRepository.cs
Public interface IRepository where T: BaseEntity {IEnumerable GetAll (); T Get (int Id); void Insert (T entity); void Update (T entity); void Delete (T entity); void Remove (T entity); void SaveChanges ();}
Repository.cs
Public class Repository: IRepository where T: BaseEntity {private readonly ApplicationDbContext _ applicationDbContext; private DbSet entities; public Repository (ApplicationDbContext applicationDbContext) {_ applicationDbContext = applicationDbContext; entities = _ applicationDbContext.Set ();} public void Delete (T entity) {if (entity = = null) {throw new ArgumentNullException ("entity");} entities.Remove (entity) _ applicationDbContext.SaveChanges ();} public T Get (int Id) {return entities.SingleOrDefault (c = > c.Id = = Id);} public IEnumerable GetAll () {return entities.AsEnumerable ();} public void Insert (T entity) {if (entity = = null) {throw new ArgumentNullException ("entity") } entities.Add (entity); _ applicationDbContext.SaveChanges ();} public void Remove (T entity) {if (entity = = null) {throw new ArgumentNullException ("entity");} entities.Remove (entity);} public void SaveChanges () {_ applicationDbContext.SaveChanges () } public void Update (T entity) {if (entity = = null) {throw new ArgumentNullException ("entity");} entities.Update (entity); _ applicationDbContext.SaveChanges ();}} 4. Implementation service layer
The service layer is used to implement the core business logic. Similarly, create a directory CustomerService to facilitate injection, which is also an interface and a class:
ICustomerService.cs
Public interface ICustomerService {IEnumerable GetAllCustomers (); Customer GetCustomer (int id); void InsertCustomer (Customer customer); void UpdateCustomer (Customer customer); void DeleteCustomer (int id);}
CustomerService.cs
Public class CustomerService: ICustomerService {private IRepository _ repository; public CustomerService (IRepository repository) {_ repository = repository;} public IEnumerable GetAllCustomers () {return _ repository.GetAll ();} public Customer GetCustomer (int id) {return _ repository.Get (id);} public void InsertCustomer (Customer customer) {_ repository.Insert (customer) } public void UpdateCustomer (Customer customer) {_ repository.Update (customer);} public void DeleteCustomer (int id) {Customer customer = GetCustomer (id); _ repository.Remove (customer); _ repository.SaveChanges ();}} 4. Inject
Here is the routine, do not explain.
Public void ConfigureServices (IServiceCollection services) {services.AddScoped (typeof (IRepository), typeof (Repository)); services.AddTransient ();} 5. Implement the controller
All three important layers have been implemented. Here is a demonstration controller:
CustomerController.cs
[ApiController] [Route ("[controller]")] public class CustomerController: ControllerBase {private readonly ICustomerService _ customerService; public CustomerController (ICustomerService customerService) {_ customerService = customerService;} [HttpGet (nameof (GetCustomer))] public IActionResult GetCustomer (int id) {var result = _ customerService.GetCustomer (id); if (result! = null) {return Ok (result) } return BadRequest ("No records found");} [HttpGet (nameof (GetAllCustomer))] public IActionResult GetAllCustomer () {var result = _ customerService.GetAllCustomers (); if (result! = null) {return Ok (result);} return BadRequest ("No records found") } [HttpPost (nameof (InsertCustomer))] public IActionResult InsertCustomer (Customer customer) {_ customerService.InsertCustomer (customer); return Ok ("Data inserted");} [HttpPut (nameof (UpdateCustomer))] public IActionResult UpdateCustomer (Customer customer) {_ customerService.UpdateCustomer (customer); return Ok ("Updation done") } [HttpDelete (nameof (DeleteCustomer))] public IActionResult DeleteCustomer (int Id) {_ customerService.DeleteCustomer (Id); return Ok ("Data Deleted");}}
Part of the code is complete.
At this point, I believe you have a deeper understanding of "how to use the Dotnet onion architecture". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.