Where does Web API fit in a typical n-tier architecture?

Sergey Akopov picture Sergey Akopov · Jul 12, 2012 · Viewed 9k times · Source

Usually when i layout an n-tier architecture for a project I have the following layers:

  • Domain (domain model, repository contracts)
  • Data (repositories working on top of domain model)
  • Service (aggregates repos, caching, validation)
  • Presentation (the mvc app)

Where would ASP.NET MVC 4 Web API fit into this considering that it will be used by the actual application and outside clients? Is it part of the service layer or does it use the service layer and sits at the same level with the MVC app?

Answer

Darin Dimitrov picture Darin Dimitrov · Jul 12, 2012

There could be 2 approaches:

  1. You decide to consume your Web API from the MVC application through HTTP calls. In this case the calling code (HttpClient) sits in your Data layer. Whether you are fetching your data from a database or a remote web service call it shouldn't really matter. In this case since the Web API probably already encapsulate much of the business logic your service layer will be very thin, just a wrapper around the data access layer, or even non-existent if it doesn't bring any additional value.

  2. Since the Web API is written in .NET you could decide to directly reference the assembly containing the service layer of this API in your MVC application. In this case the service layer of your Web API application becomes the service layer of your MVC application.