I am currently using IoC for providing concrete implemenations of repositories in a project. All of the examples that I have read use an interface as the definition of the service. However, having read recommendations from Microsoft it is recommended to prefer abstract classes over interfaces.
I have found this useful in conjuntion with the template pattern to reduce repetition. For example give a Product
class with a property IsActive
I could use an interface for the repository such as:
interface IProductRepository
{
IEnumerable<Product> Load();
}
If a common task is to load active products then I would need to do:
IEnumerable<Product> activeProducts = repository.Load().Where(x => x.IsActive);
Where repository
is a concrete implementation. If I used an abstract class such as:
abstract class ProductRepository
{
protected abstract IEnumerable<Product> LoadCore();
public IEnumerable<Product> Load()
{
return LoadCore().Where(x => x.IsActive);
}
}
Then I could load active products using
IEnumerable<Product> activeProducts = repository.Load();
All the implementation for loading the product information is within the contrete class that derives ProductRepository
so there is no coupling to the persistance layer. If it is found that there is another commonly performed activity then this could be added to the base class as a non-breaking change which could not be done using an interface.
Is there any benefit to using an interface instead of an abstract class? What potential drawbacks to using abstract classes could I come across?
I am using Castle Windsor as the IoC controller and .Net framework 3.5.