BT

Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ

Topics

Choose your language

InfoQ Homepage Articles Advanced Architecture for ASP.NET Core Web API

Advanced Architecture for ASP.NET Core Web API

This item in japanese

Bookmarks

Key Takeaways

  • 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.

Rate this Article

Adoption
Style

BT