[英]how to implement an interface with different type best practice
根据干净的架构,每一层都应该有自己的模型(最好不要在其他服务中发送相同的模型),我举个例子:
在我的 API leyer 中,我收到一个列表作为视图模型:
public class ApiLayerViewModel
{
public string QuoteId { get; set; } = default!;
public string PaymentOptionId { get; set; } = default!;
}
我有一个接口可以将其发送到另一层,即我的基础设施层:
public Task<bool> StoreConvertesCurrenciesAsync(List<ApiLayerViewModel> xyz);
我想在我的基础设施层实现这个,所以我要在那里创建另一个类(完全相同):
public class InfraLayerLayer
{
public string QuoteId { get; set; } = default!;
public string PaymentOptionId { get; set; } = default!;
}
在这里我想实现我的界面,但不能因为我的界面需要我在签名中放入的相同型号名称
public class RepoInInfrstructureLayerIRepoInApiLayer: IRepoInApiLayer
{
public Task<bool> StoreConvertesCurrenciesAsync(List<InfraLayerLayer> xyz) => throw new NotImplementedException();
}
我建议您的所有函数,无论是在 API 中还是在其他地方,都使用接口类型作为输入参数,而不是具体类型。
public interface IViewModel
{
string QuoteId { get; set; };
string PaymentOptionId { get; set; };
}
public class ApiLayerViewModel : IViewModel
{
public int APISpecificReference{get;set;}
public string QuoteId { get; set; } = default!;
public string PaymentOptionId { get; set; } = default!;
}
public class InfraLayerViewModel : IViewModel
{
public int InfraLayerSpecificReference{get;set;}
public string QuoteId { get; set; } = default!;
public string PaymentOptionId { get; set; } = default!;
}
public class RepoInInfrstructureLayerIRepoInApiLayer: IRepoInApiLayer
{
public Task<bool> StoreConvertesCurrenciesAsync(List<IViewModel> xyz) => throw new NotImplementedException();
}
然后你可以有类似的东西:
IViewModel MapAPIToInfraLayer(IViewModel param)
{
var result = new InfraLayerViewModel();
result.QuoteId=param.QuoteId;
result.PaymentOptionId=param.PaymentOptionId;
result.InfraLayerSpecificReference = 0;//this layer specific data could be added
return result;
}
我要指出的是,如果QuoteId
和PaymentOptionId
是索引引用,则它们可用于从 API 获取该索引的整个记录,以便您可以将其映射到 InfraLayer 存储库所需的记录,因为随着时间的推移,这些索引可能不匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.