Inheritance in EF Core (TBH, TPT, TPC) is a nice feature for entities which have many in common. But I am often arguing with a colleague about the design of business logic layer.
Entities:
public class FruitEntity {}
public class AppleEntity : FruitEntity {}
public class PearEntity : FruitEntity {}
We use the Repository Pattern to access the data (data access layer).
Now how to design the Business Logic Layer?
My approach is simple, separate and make a Service for each Entity.
AppleService
public class AppleService
{
private readonly IRepository<AppleEntity> _appleRepository;
public AppleService(IRepository appleRepository) {
_appleRepository = appleRepository ?? throw new ArgumentNullException();
}
public async Task<AppleEntity> GetAsync(Guid appleId)
{
//more business logic
return await _appleRepository.GetAsync(appleId);
}
}
PearService
public class PearService
{
private readonly IRepository<AppleEntity> _pearRepository;
public PearService (IRepository pearRepository) {
_pearRepository = pearRepository?? throw new ArgumentNullException();
}
public async Task<PearEntity> GetAsync(Guid pearId)
{
//more business logic
return await _pearRepository.GetAsync(pearId);
}
}
In my opinion: Its clearly separated and if we want to change any of the services we don't have any overlap between Pear and Apple use cases. So its all about single responsibility principle. Cons: One of the arguments of my colleague is the overhead while testing. We need to test every method which are nearly identical. To avoid the test overhead we could make an abstract class for the services. Alternative design of the business logic layer:
public abstract class FruitService{}
public class AppleService : FruitService{}
public class PearService : FruitService{}
I guess most of the code will be delegates. Therefore the test overhead will be smaller, best case half of all.
Are there any other styles, pattern, designs I could or should approach?