سؤال

I'm starting a new asp.net mvc core project and for my infrastructure layer I'd like to use WebAPI as this layer should be usable in other solutions besides this one.

I'm not really experienced with that and at the moment I'm thinking of having 2 contracts and 2 implementations for them in the infrastructure layer e.g:

public interface IUserService
{
    int Add(UserDTO user);
    UserDTO Update(UserDTO user);
    UserDTO Remove(UserDTO user);
    UserDTO Get(int id);
}

public interface IUserWebService
{
    int Add(UserDTO user);
    UserDTO Update(UserDTO user);
    UserDTO Remove(UserDTO user);
    UserDTO Get(int id);
}

Where the first one is the one that will be injected in the controllers in the presentation layer and the second one is the one that will be implemented by the WebAPI.

Then the implementation goes like this, the web api simply implements the IUserWebService along with the crud operations just as usual and then another type is created UserService which implements IUserService, which will serve only as a wrapper for the webapi implementation. The reason being invoking the webapi is a bit lengthy and this way that part of the logic will be isolated in this extra class.

This seems reasonable to me, but I'm not sure if it's the proper way to go, any advises would be welcome.

هل كانت مفيدة؟

المحلول

I don't think there is anything intrinsically wrong with anything you've stated. If I were to make some recommendations they would be the following, in no particular order.

  1. Structure the service contract around your workflow, not around CRUD operations. It's easy to write CRUD services, but they are seldom what you want long term. Take user create, for example. It is very rare to create a record for a user and that's it. Is there a signup flow? What steps are there? Structure the service contract around that.
  2. Interfaces are a wonderful tool, but only create them where you know there will be multiple implementations. If you only know about one implementation, write the class and be mindful of public/private modifiers. You can extract the interface later if you discover that multiple implementations are possible. This keeps your code simpler and easier to follow.
  3. WebAPI is a wonderful tool for building HTTP based systems. It is flexible to write either RPC or REST style interfaces, so spend a little time to determine which one you want to build and stay consistent with it.
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top