Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 284
Rushino Avatar asked Jan 27 '11 13:01

Rushino


People also ask

Is repository a service layer?

Repository layer is implemented to access the database and helps to extend the CRUD operations on the database. Whereas a service layer consists of the business logic of the application and may use the repository layer to implement certain logic involving the database.

Which property validates against the data annotations specified in the model on service layer?

The System. ComponentModel. DataAnnotations namespace includes the following validator attributes: Range – Enables you to validate whether the value of a property falls between a specified range of values.


1 Answers

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);
    }
}
like image 120
Darin Dimitrov Avatar answered Nov 15 '22 11:11

Darin Dimitrov