C# 如何基于枚举参数获得正确的服务?
我有一个如下的实现。代码只是用来解释问题,不是真正的实现。我有多个数据存储库,我只想有一个数据服务,我想在我的控制器中注入和使用该数据服务,但我不希望在我的实现中有类似的切换情况。有没有更好的方法或设计?或者有什么建议? 任何更好的设计都是受欢迎的。提前谢谢C# 如何基于枚举参数获得正确的服务?,c#,.net,.net-core,C#,.net,.net Core,我有一个如下的实现。代码只是用来解释问题,不是真正的实现。我有多个数据存储库,我只想有一个数据服务,我想在我的控制器中注入和使用该数据服务,但我不希望在我的实现中有类似的切换情况。有没有更好的方法或设计?或者有什么建议? 任何更好的设计都是受欢迎的。提前谢谢 interface IDataService<T> { Task<T> Get(RepoTypes repoType); } class DataService<T>:IDataService&
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
}
接口IDataService
{
任务获取(RepoTypes repoType);
}
类数据服务:IDataService
{
私有只读IRepository存储库;
私人只读电子存储库;
私人只读存储库;
专用只读IMapper\u映射器;
公共类名(IRepository xRepository,
我相信我的话,
i假定的zRepository,
IMapper(映射器)
{
_xRepository=xRepository;
_yRepository=yRepository;
_zRepository=zRepository;
_映射器=映射器;
}
公共异步任务GetTask(RepoTypes repoType)
{
交换机(repoTypes)
{
案例十:
var data=awaitxrepository.Get();
返回_mapper.Map(数据);
案例Y:
var data=await_yRepository.Get();
返回_mapper.Map(数据);
案例Y:
var data=awaitzrepository.Get();
返回_mapper.Map(数据);
违约:
}
}
}
界面假定
{
任务Get();
}
类IRepository:IRepository
{
公共异步任务GetTask()
{
//一些实现
}
}
公共枚举类型
{
X,,
Y
Z
}
没有任何细节,很难给你一个答案。此外,示例代码不可编译和/或不正确
我也有很多关于架构的问题,但我不知道要提供一个正确或令人满意的答案真的很难
至少让我试一下,也许能帮你摆脱switch语句。一种可能的方法是简单地将值存储为键值对,并在Get(RepoTypes repoType)
中检索这些值,例如,您可以将DataService
类重新指定用途,如下所示:
公共类数据服务:IDataService
{
专用只读IMapper\u映射器;
私人词典;
公共数据服务(IRepository xRepository,
我相信我的话,
i假定的zRepository,
IMapper(映射器)
{
_映射器=映射器;
_dict=新词典
{
{RepoTypes.X,xRepository},
{RepoTypes.Y,yRepository},
{RepoTypes.Z,zRepository}
};
}
公共异步任务Get(RepoTypes repoType)
{
var repo=_dict[repoType];
var data=wait repo.Get();
返回_mapper.Map(数据);
}
}
由于不同的IRepository
接口之间的类型差异,除了:dictionary
谢谢,这只是一种伪代码,我不希望编译,但我理解正确。谢谢你的帮助。