Search code examples
c#dependency-injectionsolid-principles

Is it a dependency Injection anti-pattern a base class with many constructors?


I thought about doing a base class to centralize all properties that can be used in the child classes when needed.

My question is whether what I'm doing is an dependency Injection anti-pattern.

If so, could you give examples of what would be best to maintain the dependency injection pattern and SOLID principles?

Base Class

public class BaseClass
    {
        protected readonly IProductRepository _productoRepository;
        protected readonly ICategoryRepository _categoryRepository;
        protected readonly IImageRepository _imageRepository;

        public BaseClass(IProductRepository productoRepository)
        {
            _productoRepository = productoRepository;
        }

        public BaseClass(ICategoryRepository categoryRepository)
        {
            _categoryRepository = categoryRepository;
        }

        public BaseClass(IImageRepository imageRepository)
        {
            _imageRepository = imageRepository;
        }
    }

Product child class

public class ProductClass : BaseClass
    {

        public ProductClass(IProductRepository productoRepository) : base(productoRepository)
        {

        }

        public ProductClass(ICategoryRepository categoryRepository) : base(categoryRepository)
        {

        }

        public ProductClass(IImageRepository imageRepository) : base(imageRepository)
        {

        }

    }

Category child class

public class CategoryClass : BaseClass
    {
        //Only this constructor will be required in this class
        public CategoryClass(ICategoryRepository categoryRepository) : base(categoryRepository)
        {

        }
    }

Thank you for your attention to this matter!


Solution

  • In the code you shared, there does not seem to be a justification for the use of inheritance to start with.

    DI and IOC are not at odds with inheritance patterns, but SRP is clearly violated in your base class.