JTunney
JTunney

Reputation: 904

Using MVC5 Repository pattern but need advice on where to put business logic

My latest MVC solution consists of an MVC5 site and a DAL class library that will contain a repository interface and class for each entity. I am trying to figure out where to place business logic for my entities such as CheckingAccount.Withdrawl or CheckingAccount.Deposit. Any suggestions? Should this be done within the Model folder within the MVC project while all of the repository classes are in my DAL?

Upvotes: 0

Views: 2154

Answers (2)

Mark Shevchenko
Mark Shevchenko

Reputation: 8197

If something is not an entity and is not a value object, then it's a service. Correct namespace for service depends on his level. Data-access services may be located in the Project.Dal or Project.Dal.Services. The good namespace for domain's service is the Project.Domain.Services.

Upvotes: 1

Joseph Woodward
Joseph Woodward

Reputation: 9281

Ideally you want to separate your actual business logic from your entities and abstract it away from your database or ORM as much as possible by creating a business logic layer and injecting your repository into your service/business logic layer using an IoC container and dependency injection.

The common approach is to create a separate class library for your business logic layer that remains agnostic of your UI layer (meaning your UI layer could be an MVC front end or even restful web service) and communicates via data transfer objects.

Here is a simple example:

MVC Controller / UI

public class AccountCheckingController : Controller
{

    private readonly IAccountService AccountService;

    public CheckingAccountController(IAccountService accountService)
    {
        this.AccountService accountService;
    }

    [HttpPost]
    public ActionResult Deposit(decimal depositAmount)
    {
        ...
        DepositReceiptDto depositReceipt = this.accountServive.Deposit(accountId, depositAmount);
        ...

        return new DepositViewModel {
            Receipt = depositReceipt
        }
    }

}

Business Logic Class / Service (stored in a class library such as WebsiteName.Services or Website.BusinessLogic

public class AccountService : IAccountService
{

    private readonly IAccountRepository Repository;

    public AccountService(IAccountRepository repository)
    {
        this.Repository = repository;
    }

    public DepositReceiptDto Deposit(int accountId, decimal depositAmount)
    {
        // Perform actions against your repository/ORM here.

        return new DepositReceiptDto {
            DepositAmount = depositAmount,
            User = UserDto,
            Status = Status.Success
        };
    }

    ...

}

As you can see, by using this separation you can easily switch out your UI without having to perform much work.

I hope this helps.

Upvotes: 3

Related Questions