What is a good example of a service layer in ASP.NET MVC?
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开发者_运维技巧 what should it be decoupled ?
Thanks.
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);
}
}
精彩评论