首页 > 解决方案 > 如何根据枚举参数获得正确的服务?

问题描述

我有一个如下的实现。该代码仅用于解释问题,它不是真正的实现。我有不止一个数据存储库,我只想有一个数据服务,我想在我的控制器中注入和使用该数据服务,但我不喜欢在我的实现中使用这种开关盒。有没有更好的方法或设计呢?或者有什么建议?任何更好的设计总是受欢迎的。提前致谢。

interface IDataService<T>
{
    Task<T> Get(RepoTypes repoType);
}

class DataService<T>:IDataService<T>
{
    private readonly IRepository<X> _xRepository;
     private readonly IRepository<Y> _yRepository;
    private readonly  IRepository<Z> _zRepository;
    private readonly  IMapper _mapper;

    public ClassName(IRepository<X> xRepository,
    IRepository<Y> yRepository,
    IRepository<Z> zRepository,
    IMapper mapper)
    {
        _xRepository = xRepository;
        _yRepository = yRepository;
        _zRepository = zRepository;
        _mapper = mapper;
    }
    public async Task<T>  GetTask(RepoTypes repoType)
    {
        switch (repoTypes)
        {
            case X:
                var data = await _xRepository.Get();
                return _mapper.Map<T>(data);
            case Y:
                var data = await _yRepository.Get();
                return _mapper.Map<T>(data);
            case Y:
                var data = await _zRepository.Get();
                return _mapper.Map<T>(data);
            default:
        }
    }
}

interface IRepository<T>
{
    Task<T> Get();
}
class IRepository<T>: IRepository<T>
{
    public async Task<T>  GetTask()
    {
        // some implementation
    }
}

public enum RepoTypes
{
    X,
    Y,
    Z
}

标签: c#.net.net-core

解决方案


没有任何细节很难给你答案。此外,示例代码不可编译和/或不正确。

我也有很多关于架构的问题,但不知道很难提供正确或令人满意的答案。

让我至少尝试一下,也许可以帮助您摆脱 switch 语句。一种可能的方法是简单地将值存储为键值对并在 中检索这些值Get(RepoTypes repoType),例如,您可以重新调整DataService类的用途,如下所示:

public class DataService<T> : IDataService<T>
{
  private readonly IMapper _mapper;

  private Dictionary<RepoTypes, dynamic> _dict;

  public DataService(IRepository<ClassX> xRepository,
                     IRepository<ClassY> yRepository,
                     IRepository<ClassZ> zRepository,
                     IMapper mapper)
  {
    _mapper = mapper;

    _dict = new Dictionary<RepoTypes, dynamic>
    {
      { RepoTypes.X, xRepository },
      { RepoTypes.Y, yRepository },
      { RepoTypes.Z, zRepository }
    };
  }

  public async Task<T> Get(RepoTypes repoType)
  {
    var repo = _dict[repoType];
    var data = await repo.Get();
    return _mapper.Map<T>(data);
  }
}

由于不同接口之间的类型差异IRepository,除了:Dictionary<RepoTypes, dynamic>.


推荐阅读