Pergunta
I find myself lately implementing the same concept twice, once at a low level and once at a higher level. Let me see if I can explain it...
For example, given the notion of a database, I have one interface (say IDatabase
) with methods like
void AddCompany(Company company);
which is what I consider "low level".
However, there are cases where I need to group a few of these calls (say I'm adding both a company and a user). I don't want to pollute the low level interface / implementation with this method, especially since this method basically only groups a few IDatabase
calls, so I create a new interface. My problem is: what do I call this new interface? IHighLevelDataAccess
just sounds weird.
I have the same problem with, say, remote access. One interface / implementation for the raw calls (one method maps to one web call) and another one for more complex logic (but mostly still doing remote calls).
Is there a naming convention that is expected / recommended in such cases? A design pattern that eludes me?
Solução
As @Ewan mentioned his comment, you need Repository Layer and Service Layer.
I also prefer adding Facade Layer in Service Layer. By this way, you can begin a transaction and can call kind of methods even they are not related.
For example, you have UserService
and CompanyService
. Normally, there is not required to create User
and Company
same time but you want to do that. So, create a facade CompanyFacade
, which acts like other services but there is no or less business code, add a method CreateCompanyByAddingUser
and begin transaction there.
public class CompanyFacade
{
private readonly ICompanyService _companyService;
private readonly IUserService _userService;
private readonly Context _context;
public CompanyFacade(Context context, ICompanyService companyService, IUserService userService)
{
_context = context;
_companyService = companyService;
_userService = userService;
}
public void CreateCompanyByAddingUser(CompanyAndUserDTO dto)
{
using (_context.BeginTransaction())
{
_userService.Create(dto.User);
_companyService.Create(dto.Company);
_context.Commit();
}
}
}
You can add various methods like that.