I have some logic like this, before save the stock into the db, i will check whether there is stock has the same stock code in the database. My question is where should I put the logic, in the service layer or repository layer. here is the sample code:
option 1: put in the service layer, i put the IsAccountAlreadyExists Method in the service layer
public override void Save(AccountInfo accountInfo)
{
using (var scope = new TransactionScope())
{
if(this.IsAccountAlreadyExists(accountInfo))
{
throw new AccountAlreadyExistedException(
"Account Code : " + accountInfo.AccountCode +
" already existed.");
}
accountRepository.Save(accountInfo);
scope.Complete();
}
}
option 2: I will move the IsAccountAlreadyExists logic to the repository layer.
public override void Save(AccountInfo accountInfo)
{
try
{
using (var scope = new TransactionScope())
{
accountRepository.Save(accountInfo);
scope.Complete();
}
}
catch(AccountAlreadyExistedException e)
{
...
}
}
what's your opinion?
Data validation should occur in two locations: The point where data is acted upon, for example validating input parameters to an SQL query. General validation at the point where data is submitted, for example in a web application some validation should occur on the client.
As a general rule of thumb, I would say that business logic of this sort should be in the service. Controllers should be light-weight and pass on requests. Further, there may be other clients of your service, not just controllers, so this allows you to keep validation in one place.
The service layer contains business logic. In particular, it contains validation logic.
A service layer is a layer in an application that facilitates communication between the controller and the persistence layer. Additionally, business logic is stored in the service layer. It includes validation logic in particular.
I consider this to be three tiers (with an interface defined to connect each piece):
This way, if you choose to store your data in some other fashion, the validation logic doesn't get lost with it.
Similarly, if you decide to provide a different form of client access, you do it without needing to replicate a bunch of logic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With