它是一个依赖注入反模式,它是具有许多构造函数的基类吗?

问题描述 投票:-1回答:2

我考虑过做一个基类来集中需要时可以在子类中使用的所有属性。

我的问题是我在做什么,是否是依赖项注入反模式。

如果是这样,您能否举例说明最好的方法来维持依赖项注入模式和SOLID原则?

基础类

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;
        }
    }

产品子类

public class ProductClass : BaseClass
    {

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

        }

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

        }

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

        }

    }

类别子类别

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

        }
    }

谢谢您对此事的关注!

c# dependency-injection solid-principles
2个回答
0
投票
all存储库:

public class BaseClass { protected readonly IProductRepository _productoRepository; protected readonly ICategoryRepository _categoryRepository; protected readonly IImageRepository _imageRepository; public BaseClass(IProductRepository productoRepository, ICategoryRepository categoryRepository, IImageRepository imageRepository) { _productoRepository = productoRepository; _categoryRepository = categoryRepository; _imageRepository = imageRepository; } 这使它成为非常标准和明智的方式来为依赖注入设置自己。

如果您确实确实希望每个类拥有一个不同的repo实例,那么最好引入一个更通用的IRepository并对其进行DI处理:

public class BaseClass { protected readonly IRepository _repository; public BaseClass(IRepository repository) { _repository= repository; }

如果您希望对派生类中所需的实现有更多的控制,则可以选择泛型:

public interface IRepository { }
public interface IProductRepository : IRepository { } // you can inherit interfaces
public interface ICategoryRepository : IRepository { }
public interface IImageRepository : IRepository { }

public class BaseClass<TRepo>  where TRepo : IRepository // we will require all generic parameters to be descendant of base interface
{
    protected readonly TRepo _repo;

    public BaseClass(TRepo repo)
    {
        _repo = repo;
    }
}

class Category : BaseClass<ICategoryRepository> {

    public Category(ICategoryRepository repo) : base(repo) {} // DI will inject a specific implementation
}

希望概述的示例适用于您


-1
投票
DI和IOC与继承模式没有矛盾,但是在您的基类中显然违反了SRP。
© www.soinside.com 2019 - 2024. All rights reserved.