转自:

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的更多相关文章

  1. 使用 Swagger 自动生成 ASP.NET Core Web API 的文档、在线帮助测试文档(ASP.NET Core Web API 自动生成文档)

    对于开发人员来说,构建一个消费应用程序时去了解各种各样的 API 是一个巨大的挑战.在你的 Web API 项目中使用 Swagger 的 .NET Core 封装 Swashbuckle 可以帮助你 ...

  2. 在ASP.NET Core Web API上使用Swagger提供API文档

    我在开发自己的博客系统(http://daxnet.me)时,给自己的RESTful服务增加了基于Swagger的API文档功能.当设置IISExpress的默认启动路由到Swagger的API文档页 ...

  3. Docker容器环境下ASP.NET Core Web API应用程序的调试

    本文主要介绍通过Visual Studio 2015 Tools for Docker – Preview插件,在Docker容器环境下,对ASP.NET Core Web API应用程序进行调试.在 ...

  4. 在docker中运行ASP.NET Core Web API应用程序

    本文是一篇指导快速演练的文章,将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤,在介绍的过程中,也会对docker的使用进行一些简单的描述.对于.NET Cor ...

  5. ASP.NET Core Web API Cassandra CRUD 操作

    在本文中,我们将创建一个简单的 Web API 来实现对一个 “todo” 列表的 CRUD 操作,使用 Apache Cassandra 来存储数据,在这里不会创建 UI ,Web API 的测试将 ...

  6. 在Mac下创建ASP.NET Core Web API

    在Mac下创建ASP.NET Core Web API 这系列文章是参考了.NET Core文档和源码,可能有人要问,直接看官方的英文文档不就可以了吗,为什么还要写这些文章呢? 原因如下: 官方文档涉 ...

  7. ASP.NET Core Web API 开发-RESTful API实现

    ASP.NET Core Web API 开发-RESTful API实现 REST 介绍: 符合REST设计风格的Web API称为RESTful API. 具象状态传输(英文:Representa ...

  8. Docker容器环境下ASP.NET Core Web API

    Docker容器环境下ASP.NET Core Web API应用程序的调试 本文主要介绍通过Visual Studio 2015 Tools for Docker – Preview插件,在Dock ...

  9. docker中运行ASP.NET Core Web API

    在docker中运行ASP.NET Core Web API应用程序 本文是一篇指导快速演练的文章,将介绍在docker中运行一个ASP.NET Core Web API应用程序的基本步骤,在介绍的过 ...

随机推荐

  1. HBase Hive

    Hbase数据管理 Hbase就是Hadoop database Hbase是列式数据库 因此Hbase特别适合寻找按照时间排序寻找Top n的场景 Hive数据管理 基于 Hadoop 文件系统的数 ...

  2. 群晖DSM修改ssh权限实现免密码登陆

    问题 使用ssh-id-copy正确上传公钥后依然无法免密码登陆 原因 群晖DSM中.ssh文件夹权限不当 解决 赋予正确权限 admin@DiskStation:/var/services/home ...

  3. 性能优化-css,js的加载与执行

    前端性能优化 css,js的加载与执行 javascript是单线程的 一个网站在浏览器是如何进行渲染的呢? html页面加载渲染的过程 html渲染过程的一些特点 顺序执行,并发加载 词法分析 并发 ...

  4. 下载 Microsoft JDBC driver 7.2 for SQL Server

    下载 Microsoft JDBC driver 7.2 for SQL Server:https://www.microsoft.com/zh-cn/download/confirmation.as ...

  5. 设置display:inline-block 元素间隙

    上代码: <div class="page"> <a href="" class="num">共1231条</ ...

  6. CodeForces 1144A

    原题链接:https://vjudge.net/problem/CodeForces-1144A #include<bits/stdc++.h> using namespace std; ...

  7. vue.js中使用离线检测

    Html5在window.navigator对象上添加了一个属性onLine 返回布尔值 true表示在线.同时新增了两个事件: window.addEventListener('online', f ...

  8. Vuex项目实战store

    首先简单了解一下什么是Vuex? Vuex是一个专为Vue.js应用程序开发的状态管理模式.采用集中式存储来管理应用所有组件的状态. 以下是对vuex的使用的简单介绍: 一.安装 npm i vuex ...

  9. git本地仓库远程仓库地址更改

    git remote rm origingit remote add origin git@52.82.8.87:iot3.0-service/test.gitgit push -u origin - ...

  10. VM中Linux网络设置(固定ip、连接外网开发环境)

      在开发过程中,我们经常需要在linux中进行操作.毕竟服务器的系统大多数都是Linux,所以在dev环境需要配置好一台Linux系统配合开发.   在VMWare Workstation Pro中 ...