What is a good example of a service layer in ASP.NET MVC?

前端 未结 1 1267
遥遥无期
遥遥无期 2021-02-01 11:36

i would love to know what is a good example (provide some code) of a service layer in ASP.NET MVC ?

  • What exactly it should include and contains ?
  • From wha
相关标签:
1条回答
  • 2021-02-01 11:49

    The service layer should contain business operations and it should be decoupled from the data access layer (repositories). The service layer exposes business operations which could be composed of multiple CRUD operations. Those CRUD operations are performed by the repositories. So for example you could have a business operation which would transfer some amount of money from one account to another and in order to perform this business operation you will need first to ensure that the sender account has sufficient provisions, debit the sender account and credit the receiver account. The service operations could also represent the boundaries of SQL transactions meaning that all the elementary CRUD operations performed inside the business operation should be inside a transaction and either all of them should succeed or rollback in case of error.

    In order to decouple the service layer from the underlying data access layer you could use interfaces:

    public class BankService
    {
        private readonly IAccountsRepository _accountsRepository;
        public OrdersService(IAccountsRepository accountsRepository)
        {
            _accountsRepository = accountsRepository;
        }
    
        public void Transfer(Account from, Account to, decimal amount)
        {
            _accountsRepository.Debit(from, amount);
            _accountsRepository.Credit(to, amount);
        }
    }
    
    0 讨论(0)
提交回复
热议问题