API architecture overview

I’ve cleaned up the controller which contained everything. It took a while because I’ve split one project into quite a few. The current structure is the following:

  • Common – as there is always something in common… Currently there is only a little stuff for exceptions there.
  • Controllers – controllers only. They have services injected, but know only their interfaces.
  • Main – the root where routing and dependency injection are defined.
  • Models – classes reflecting database documents. They are used only in repositories and for mapping into view models.
  • Repositories.Interfaces – interfaces of repositories, injected into services.
  • Repositories – classes which talk to the database. They use models, but only for the purpose of queries. The external world needs only some part of the data (or combinations of different models), so models are immediately transformed into view models.
  • Services.Interfaces – only interfaces of services, so that controllers don’t know the implementation.
  • Services – services themselves.
  • ViewModels – classes used by services and passed into/out of controllers. Actually there is no “view” in Web API, but I’m not convinced that they should be called DTOs since there might be some logic inside in the future as well.

And a picture, because a picture is worth more than 1000 words:
API structure
The diagram was created using https://www.draw.io/.

I was a bit unsure of where to put conversion between models and view models. My first thought was to perform it in MongoDB projection, but view models can aggregate data from several models. Such projection would be impossible since there are no joins possible in a query. So view models will eventually be responsible for that themselves.

One good thing I’ve done thanks to this answer on StackOverflow was converting MongoDB’s ObjectId to string right in a query. So instead of having a property of type ObjectId in a model, I can have it as a string and then a view model, when mapping, doesn’t have to know that the model uses MongoDB:

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s