Should I share types between a Web API service and its client ? What are the other options?

后端 未结 3 1346
南笙
南笙 2021-01-30 20:15

We are developing a Web API RESTful service to provide access to common data to all the applications of our enterprise. To help we will also publish a Client API that encapsulat

3条回答
  •  旧巷少年郎
    2021-01-30 21:09

    Domain model classes are primarily defined to be used by the server. On the server side, model types are used by the methods defined inside controllers to access data, for example by using entity framework.

    But, for some reasons you may prefer to pass another version of the model object to the client. A known approach is to define DTO classes which are very similar but not exactly the same as model types.

    In each method in the controller, when you fetch data from database, you need to map the retrieved data from its model type format to its comparable DTO class. AutoMapper makes this mapping easier.

    Therefore you need these steps to be done:

    1. Define your model types inside the server project.
    2. Add these packages to your server project as dependencies:
      • AutoMapper
      • AutoMapper.Extensions.Microsoft.DependencyInjection (version 1.2.0)
    3. Define a MappingProfile (or MappingConfiguration) inside the server project and use services.AddAutoMapper() in ConfigureServices method in Startup.cs
    4. Modify your controller methods to do proper mapping on the retrieved data and return equivalent DTO as the output of the method.
    5. In parallel, you can make a new project containing your DTO classes. This project is shared between server and client projects.

    Then, on the client side you do not need to know any details of model types. Your client only works with DTO classes. These classes contain all the necessary data on the client side. In some cases you may need to combine data of multiple model objects to provide a single container for client side.

提交回复
热议问题