Advanced Architecture for ASP.NET Core Web API
转自:
https://www.infoq.com/articles/advanced-architecture-aspnet-core
- ASP.NET Core's new architecture offers several benefits as compared to the legacy ASP.NET technology
- ASP.NET Core benefits from incorporating support for dependency injection from the start
- Single Responsibility Principle simplifies implementation and design
- The Ports and Adapter Pattern decouples business logic from other dependencies
- Decoupled architecture makes testing much easier and more robust
With the release of .NET Core 2.0, Microsoft has the next major version of the general purpose, modular, cross-platform and open source platform that was initially released in 2016. .NET Core has been created to have many of the APIs that are available in the current release of .NET Framework. It was initially created to allow for the next generation of ASP.NET solutions but now drives and is the basis for many other scenarios including IoT, cloud and next generation mobile solutions. In this series, we will explore some of the benefits .NET Core and how it can benefit not only traditional .NET developers but all technologists that need to bring robust, performant and economical solutions to market.
This InfoQ article is part of the series ".NET Core". You can subscribe to receive notifications via RSS.
The Internet is a very different place from five years ago, let alone 20when I first started as a professional developer. Today, Web APIs connect the modern internetand drive both web applications and mobile apps. The skill of creating robust Web APIs that other developers can consume is in high demand. Our API’s that drive most modern web and mobile apps need to have the stability and reliability to stay servicing even when traffic is at the performance limits.
The purpose of this article is to describe the architecture of an ASP.NET Core 2.0 Web API solution using the Hexagonal Architecture and Ports and Adapters Pattern. First, we will look at the new features of .NET Core and ASP.NET Core that benefit modern Web API’s.
The solution and all code from this article’s examples can be foundin my GitHub repository ChinookASPNETCoreAPIHex.
.NET Core and ASP.NET Core for Web API
ASP.NET Core is a new web framework that Microsoft built on top of .NET Core to shed the legacy technology that has been around since .NET 1.0. By comparison, ASP.NET 4.6 still uses the System.Webassembly that contains all the WebForms libraries and as a result is still broughtinto more recent ASP.NET MVC 5 solutions. By shedding these legacy dependencies and developing the framework from scratch, ASP.NET Core 2.0 gives the developer much better performance and is architected for cross-platform execution. With ASP.NET Core 2.0, your solutions will work as well on Linux as they do on Windows.
You can read more about the benefits of .NET Core and ASP.NET Core from the three other articles in this series. The first is Performance isa .NET Core Feature by Maarten Balliauw, ASP.NET Core - The Power of Simplicity by Chris Klug and finally, Azure and .NET Core Are Beautiful Together by Eric Boyd.
Architecture
Building a great API depends ongreatarchitecture. We will be looking at many aspects of our API design and development from the built-infunctionality of ASP.NET Core to architecture philosophy and finally design patterns. There is muchplanning and thought behind this architecture, so let’s get started.
Dependency Injection
Before we dig into the architecture of our ASP.NET Core Web API solution, I want to discuss what I believe is a singlebenefit which makes .NET Core developers lives so much better; that is, DependencyInjection (DI). Now, I know you will say that we had DI in .NET Framework and ASP.NET solutions. I will agree, butthe DI we used in the past would be from third-party commercial providers or maybe open source libraries. They did a good job, butfor a good portion of .NET developers, there was a big learning curve, andall DI libraries had their uniqueway of handling things. Today with .NET Core, we have DI built right into the framework from the start. Moreover,it is quite simple to work with, andyou get it out of the box.
The reason we need to use DI in our API is that it allows usto have the best experience decoupling our architecture layers and also to allowus to mock the data layer, or have multiple data sources built for our API.
To use the .NET Core DI framework, justmake sure your project references the Microsoft.AspNetCore.AllNuGet package (which contains a dependency on Microsoft.Extnesions.DependencyInjection.Abstractionspackage). This package gives access to the IServiceCollection interface, which has a System.IServiceProvider interface that you can call GetService<TService>. Toget the services you need from the IServiceCollection interface, you will need to add the services your project needs.
To learn more about .NET Core Dependency Inject, I suggest you review the following document on MSDN: Introduction to Dependency Injection in ASP.NET Core.
We will now look at the philosophy of why we architected our API as I did. The two aspects of designing any architecture dependon these two ideas: allowing deep maintainability and utilizing proven patterns and architectures in your solutions.
Maintainability of the API
Maintainability for any engineering process is the ease with which a product can be maintained: finding defects, correcting found defects, repairing or replacing defective components without having to replace still-working parts, preventing unexpected malfunctions, maximizing a product's useful life, having the ability to meet new requirements, make future maintenance easier, or cope with a changing environment.Thiscan be a difficult road to go down without a well planned and executed architecture.
Maintainability is a long-term issue and should be lookedat with a vision of your API in the far distance. With that in mind,you need to make decisions that lead to this future vision and not to short-termshortcuts that seem to make life easier right now. Making hard decisions at the start will allow your project to have a long life and provide benefits that users demand.
What makes a software architecture have high maintainability? How do we evaluate if our API canbe maintained?
- Does our architecture allow for changes that have minimal if not zero impact onother areas of the system?
- Debugging of the API should be easy and not have to difficult set up to be done. We should have established patterns and be through common methods (such as browser debugging tools).
- Testing should be automated as possible and be clear and not complicated.
Interfaces and Implementations
The key to my API architecture is the use of C# interfaces to allow for alternative implementations. If you have written .NET code with C#,you have probably used interfaces. I use interfaces in my solution to build out a contract in my Domain layer that guarantees that any Data layer I develop for my API adheres to the contract for data repositories. It also allows the Controllers in my API project to adhere to another established contract for getting the correct methods to process the API methods in the domain project’s Supervisor. Interfaces are very important to .NET Core and if you need a refresher go here for more information.
Ports and Adapter Pattern
We want our objects throughout our API solution to have single responsibilities. Thiskeeps our objects simple and easily changed if we need to fix bugs or enhance our code. If you have these “code smells” in your code,then you might be violating the single responsibility principle. As a general rule, I look at the implementations of the interface contracts for length and complexity. I do nothave a limit to the lines of code in my methods,butif you passeda single view in your IDE,it might be too long. Also,check the cyclomatic complexity of your methods to determine the complexity of your project’s methods and functions.
The Ports and Adapter Pattern (aka Hexagonal Architecture) is a way to fix this problem of having business logic coupled too tightly to other dependencies such as data access or API frameworks. Using this pattern will allow your API solution to have clear boundaries, well-namedobjects that have single responsibilities and finally allow easier development and maintainability.
We can see the pattern best visually like an onion with ports located on the outside of the hexagon and the adapters and business logic located closer to the core. I see the external connections of the architecture as the ports. The API endpoints that are consumedor the database connection used by Entity Framework Core 2.0 would be examples of ports while the internal data repositories would be the adapters.
Next,let’s look at the logical segments of our architecture and some demo code examples.
Domain Layer
Before we look at the API and Domain layers, we need to explain how we build out the contracts through interfaces and the implementations for our API business logic. Let’s look at the Domain layer. The Domain layer has the following functions:
- Defines the Entities objects that will be usedthroughout the solution. These models will represent the Data layer’s DataModels.
- Defines the ViewModels which will be used by the API layer for HTTP requests and responses as single objects or sets of objects.
- Defines the interfaces through which our Data layer can implement the data access logic
- Implements the Supervisor that will containmethods called from the API layer. Each method will represent an API call and will convert data from the injected Data layer to ViewModels to be returned
Our Domain Entity objects are a representation of the database that we are using to store and retrieve data used for the API business logic. Each Entity object will contain the properties represented in our case the SQL table. As an exampleis the Album entity.
public sealed class Album
{
public int AlbumId { get; set; }
public string Title { get; set; }
public int ArtistId { get; set; }
public ICollection<Track> Tracks { get; set; } = new HashSet<Track>();
public Artist Artist { get; set; }
}
The Album table in the SQL database has threecolumns: AlbumId, Title, andArtistId. These three properties are part of the Album entity as well as the Artist’s name, a collection of associated Tracks and the associated Artist. As we will see in the other layers in the API architecture, we will build upon this entity object’s definition for the ViewModels in the project.
The ViewModels are the extension of the Entities and help give more information for the consumer of the APIs. Let'slook at the Album ViewModel. It is very similar to the Album Entity but with an additional property. In the design of my API, I determined that each Album should have the name of the Artist in the payload passed back from the API. Thiswill allow the API consumer to have that crucial piece of information about the Album without having to have the Artist ViewModel passed back in the payload (especially when we are sending back a large set of Albums). An example of our AlbumViewModel is below.
public class AlbumViewModel
{
public int AlbumId { get; set; }
public string Title { get; set; }
public int ArtistId { get; set; }
public string ArtistName { get; set; }
public ArtistViewModel Artist { get; set; }
public IList<TrackViewModel> Tracks { get; set; }
}
The other area that is developedinto the Domain layer isthe contracts via interfaces for each of the Entities defined in the layer. Again, we will use the Album entity to show the interface that is defined.
public interface IAlbumRepository : IDisposable
{
Task<List<Album>> GetAllAsync(CancellationToken ct = default(CancellationToken));
Task<Album> GetByIdAsync(int id, CancellationToken ct = default(CancellationToken));
Task<List<Album>> GetByArtistIdAsync(int id, CancellationToken ct = default(CancellationToken));
Task<Album> AddAsync(Album newAlbum, CancellationToken ct = default(CancellationToken));
Task<bool> UpdateAsync(Album album, CancellationToken ct = default(CancellationToken));
Task<bool> DeleteAsync(int id, CancellationToken ct = default(CancellationToken));
}
As shown in the above example, the interface definesthe methods needed to implement the data access methods for the Album entity. Each entity object and interface are well defined and simplistic that allows the next layer to be well defined.
Finally, the core of the Domain project is the Supervisor class. Itspurpose is to translate to and from Entities and ViewModels and perform business logic away from either the API endpoints and the Data access logic. Having the Supervisor handle this also will isolate the logic to allow unit testing on the translations and business logic.
Looking at the Supervisor method for acquiring and passing a single Album to the API endpoint, we can see the logic in connecting the API front end to the data access injected into the Supervisor but still keeping each isolated.
public async Task<AlbumViewModel> GetAlbumByIdAsync(int id, CancellationToken ct = default(CancellationToken))
{
var albumViewModel = AlbumCoverter.Convert(await _albumRepository.GetByIdAsync(id, ct));
albumViewModel.Artist = await GetArtistByIdAsync(albumViewModel.ArtistId, ct);
albumViewModel.Tracks = await GetTrackByAlbumIdAsync(albumViewModel.AlbumId, ct);
albumViewModel.ArtistName = albumViewModel.Artist.Name;
return albumViewModel;
}
Keeping most of the code and logic in the Domain project will allow every project to keep and adhere to the single responsibility principle.
Data Layer
The next layer of the API architecture we will look at is the Data Layer. In our example solution,we are using Entity Framework Core 2.0. Thiswill mean that we have the Entity Framework Core’s DBContext defined but also the Data Models generated for each entity in the SQL database. If we look at the data model for the Album entity as an example, we will see that we have three properties that are storedin the database along with a property that contains a list of associated tracks to the album, in addition to a property that contains the artist object.
While you can have a multitude of Data Layer implementations, justremember that it must adhere to the requirements documented on the Domain Layer; each Data Layer implementation must work with the View Models and repository interfaces detailed in the Domain Layer. The architecture we are developing for the API uses the Repository Pattern for connecting the API Layer to the Data Layer. Thisis done using Dependency Injection (as we discussed earlier) for each of the repository objects we implement. We will discuss how we use Dependency Injection and the code when we look at the API Layer. The key to the Data Layer is the implementation of each entity repository using the interfaces developed in the Domain Layer. Looking at the Domain Layer’s Album repository as an example shows that it implements the IAlbumRepository interface. Each repository will inject the DBContext that will allow for access to the SQL database using Entity Framework Core.
public class AlbumRepository : IAlbumRepository
{
private readonly ChinookContext _context;
public AlbumRepository(ChinookContext context)
{
_context = context;
}
private async Task<bool> AlbumExists(int id, CancellationToken ct = default(CancellationToken))
{
return await GetByIdAsync(id, ct) != null;
}
public void Dispose()
{
_context.Dispose();
}
public async Task<List<Album>> GetAllAsync(CancellationToken ct = default(CancellationToken))
{
return await _context.Album.ToListAsync(ct);
}
public async Task<Album> GetByIdAsync(int id, CancellationToken ct = default(CancellationToken))
{
return await _context.Album.FindAsync(id);
}
public async Task<Album> AddAsync(Album newAlbum, CancellationToken ct = default(CancellationToken))
{
_context.Album.Add(newAlbum);
await _context.SaveChangesAsync(ct);
return newAlbum;
}
public async Task<bool> UpdateAsync(Album album, CancellationToken ct = default(CancellationToken))
{
if (!await AlbumExists(album.AlbumId, ct))
return false;
_context.Album.Update(album);
_context.Update(album);
await _context.SaveChangesAsync(ct);
return true;
}
public async Task<bool> DeleteAsync(int id, CancellationToken ct = default(CancellationToken))
{
if (!await AlbumExists(id, ct))
return false;
var toRemove = _context.Album.Find(id);
_context.Album.Remove(toRemove);
await _context.SaveChangesAsync(ct);
return true;
}
public async Task<List<Album>> GetByArtistIdAsync(int id, CancellationToken ct = default(CancellationToken))
{
return await _context.Album.Where(a => a.ArtistId == id).ToListAsync(ct);
}
}
Having the Data Layer encapsulating all data access will allow facilitating a better testing story for your API. We can build multiple data access implementations: one for SQL database storage, another for maybe a cloud NoSQL storagemodel and finally a mock storage implementation for the unit tests in the solution.
API Layer
The final layer that we will look at is the area that your API consumers will interact. This layer contains the code for the Web API endpoint logic including the Controllers. The API project for the solution will have a single responsibility, andthat is only to handlethe HTTP requests received by the web server and to return the HTTP responses with either success or failure. There will be a very minimal business logic in this project. We will handle exceptions and errors that have occurred in the Domain or Data projects to effectively communicate with the consumer of APIs. This communication will use HTTP response codes and any data to be returnedlocated in the HTTP response body.
In ASP.NET Core 2.0 Web API, routing is handled using Attribute Routing. If you need to learn more about Attribute Routing in ASP.NET Core go here.We are also using dependency injection tohave the Supervisor assigned toeach Controller. Each Controller’s Action method has a corresponding Supervisor method that will handle the logic for the API call. I have a segment of the Album Controller below to show these concepts.
[Route("api/[controller]")]
public class AlbumController : Controller
{
private readonly IChinookSupervisor _chinookSupervisor;
public AlbumController(IChinookSupervisor chinookSupervisor)
{
_chinookSupervisor = chinookSupervisor;
}
[HttpGet]
[Produces(typeof(List<AlbumViewModel>))]
public async Task<IActionResult> Get(CancellationToken ct = default(CancellationToken))
{
try
{
return new ObjectResult(await _chinookSupervisor.GetAllAlbumAsync(ct));
}
catch (Exception ex)
{
return StatusCode(500, ex);
}
}
...
}
The Web API project for the solution is very simple and thin. I strive to keep as little of code in this solution as it could be replacedwith another form of interaction in the future.
Conclusion
As I have demonstrated, designing and developing a great ASP.NET Core 2.0 Web API solution takes insight in order tohave a decoupled architecture that will allow each layer to be testable and follow the Single Responsibility Principle. I hope my information will allow you to create and maintain your production Web APIs for your organization’s needs.
About the Author
Chris Woodruff (Woody) has a degree in Computer Science from Michigan State University’s College of Engineering. Woody has been developing and architecting software solutions for over 20 years and has worked in many different platforms and tools. He is a community leader, helping such events as GRDevNight, GRDevDay, West Michigan Day of .NET and CodeMash. He was also instrumental in bringing the popular Give Camp event to Western Michigan where technology professionals lend their time and development expertise to assist local non-profits. As a speaker and podcaster, Woody has spoken and discussed a variety of topics, including database design and open source. He has been a Microsoft MVP in Visual C#, Data Platform and SQL and was recognized in 2010 as one of the top 20 MVPs world-wide. Woody is a Developer Advocate for JetBrains and evangelizes .NET, .NET Core and JetBrains' products in North America.
With the release of .NET Core 2.0, Microsoft has the next major version of the general purpose, modular, cross-platform and open source platform that was initially released in 2016. .NET Core has been created to have many of the APIs that are available in the current release of .NET Framework. It was initially created to allow for the next generation of ASP.NET solutions but now drives and is the basis for many other scenarios including IoT, cloud and next generation mobile solutions. In this series, we will explore some of the benefits .NET Core and how it can benefit not only traditional .NET developers but all technologists that need to bring robust, performant and economical solutions to market.
This InfoQ article is part of the series ".NET Core". You can subscribe to receive notifications via RSS.
Advanced Architecture for ASP.NET Core Web API的更多相关文章
- 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)
对于开发人员来说,构建一个消费应用程序时去了解各种各样的 API 是一个巨大的挑战.在你的 Web API 项目中使用 Swagger 的 .NET Core 封装 Swashbuckle 可以帮助你 ...
- 在ASP.NET Core Web API上使用Swagger提供API文档
我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的API文档功能.当设置IISExpress的默认启动路由到Swagger的API文档页 ...
- Docker容器环境下ASP.NET Core Web API应用程序的调试
本文主要介绍通过Visual Studio 2015 Tools for Docker – Preview插件,在Docker容器环境下,对ASP.NET Core Web API应用程序进行调试.在 ...
- 在docker中运行ASP.NET Core Web API应用程序
本文是一篇指导快速演练的文章,将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤,在介绍的过程中,也会对docker的使用进行一些简单的描述.对于.NET Cor ...
- ASP.NET Core Web API Cassandra CRUD 操作
在本文中,我们将创建一个简单的 Web API 来实现对一个 “todo” 列表的 CRUD 操作,使用 Apache Cassandra 来存储数据,在这里不会创建 UI ,Web API 的测试将 ...
- 在Mac下创建ASP.NET Core Web API
在Mac下创建ASP.NET Core Web API 这系列文章是参考了.NET Core文档和源码,可能有人要问,直接看官方的英文文档不就可以了吗,为什么还要写这些文章呢? 原因如下: 官方文档涉 ...
- ASP.NET Core Web API 开发-RESTful API实现
ASP.NET Core Web API 开发-RESTful API实现 REST 介绍: 符合REST设计风格的Web API称为RESTful API. 具象状态传输(英文:Representa ...
- Docker容器环境下ASP.NET Core Web API
Docker容器环境下ASP.NET Core Web API应用程序的调试 本文主要介绍通过Visual Studio 2015 Tools for Docker – Preview插件,在Dock ...
- docker中运行ASP.NET Core Web API
在docker中运行ASP.NET Core Web API应用程序 本文是一篇指导快速演练的文章,将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤,在介绍的过 ...
随机推荐
- Docker最全教程——从理论到实战(二十二)
前言 最近正在抽时间编写k8s的相关教程,很是费时,等相关内容初步完成后,再和大家分享.对于k8s,还是上云更为简单.稳定并且节省成本,因此我们需要对主流云服务的容器服务进行了解,以便更好地应用于生产 ...
- stylelint
"number-leading-zero": "never", // 去掉小数点前面的0 "prettier.stylelintIntegration ...
- 使用yum安装报错:[Errno 256] No more mirrors to try
背景:我使用yum方式安装软件时,比如zabbix这种软件,我们在安装时一般都是直接到zabbix官网,按照官方的步骤进行安装,但是有一个问题,官方的服务器不在国内,时常会在安装时导致超时报错.此时解 ...
- anki
anki需要一个舞台来容纳所有的不同领域的经历 虽然难以避免臃肿的局面.
- vue报错[Vue warn]: The data property "record" is already declared as a prop. Use prop default value instead.
当我写了一个子组件,点击打开子组件那个方法时报了一个错 这句话说明意思呢?谷歌翻译一下↓ 数据属性“record”已声明为prop. 请改用prop默认值. 感觉翻译的有点怪,通过最后修改代码后大概意 ...
- npm 模块开发调试技巧之最优方案npm link
在我们平时写项目中,当我们需要新开发或修改的 npm 模块时,如何在本地项目中调试呢? 本地项目路径:G:\npm\project 开发的模块路径:G:\npm\model 方法一: 在cmd命令窗口 ...
- javaScript(Date与Math的API)
目录 Math Math的两个属性值 E PI abs(); ceil(); floor(); round(); max(); min (); pow(); random sin(); cos(); ...
- 马走日的解法(dfs)
马在中国象棋以日字形规则移动. 请编写一段程序,给定n*m大小的棋盘,以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点. Input 第一行为整数T ...
- View -->Controller传值的几种方法
1.参数名称必须和表单的name是一致的. //参数的名称需要和表单的字段名称一致,这样系统便会直接赋值. public ActionResult GetUserInfo(string usernam ...
- 傻傻分不清之 Cookie、Session、Token、JWT
傻傻分不清之 Cookie.Session.Token.JWT 什么是认证(Authentication) 通俗地讲就是验证当前用户的身份,证明“你是你自己”(比如:你每天上下班打卡,都需要通过指纹打 ...