c# - 如何根据枚举参数获得正确的服务?
问题描述
我有一个如下的实现。该代码仅用于解释问题,它不是真正的实现。我有不止一个数据存储库,我只想有一个数据服务,我想在我的控制器中注入和使用该数据服务,但我不喜欢在我的实现中使用这种开关盒。有没有更好的方法或设计呢?或者有什么建议?任何更好的设计总是受欢迎的。提前致谢。
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
}
解决方案
没有任何细节很难给你答案。此外,示例代码不可编译和/或不正确。
我也有很多关于架构的问题,但不知道很难提供正确或令人满意的答案。
让我至少尝试一下,也许可以帮助您摆脱 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>
.
推荐阅读
- azure - HDInsight 和 Hive 查询
- c# - 使用 Vimba API 实时更新图表
- django - 查询 django 迁移表
- angular - 提交搜索表单后的角度重定向
- python - 如何从 IPStack 中抓取 time_zone?
- r - 如何在新数据上使用构建分类器(基于词嵌入)进行情感分析?
- ios - 不透明度在情节提要中不起作用
- xml - Pentaho - XPath 选择具有特定父级的所有子级
- linux - 在 Jenkins 中执行 shell 命令无法识别管道字符
- javascript - 如何用多个 d.ts 文件描述现有的 JS 库,并使用 NPM 将其导出