我有一个问题,关于如何实现一种方法以能够在其他方法中使用它而无需重复代码和遵守DRY原理。让我更好地解释一下,我有更多类似的方法:
public async Task<int> AddCustomerPackageAsync(Guid customerId, CustomerPackageDto customerPackageDto)
{
var customer = await GetCustomerFromRepositoryAsync(customerId);
var customerPackage = _mapper.Map<CustomerPackage>(customerPackageDto, options =>
options.AfterMap((o, dest) =>
{
dest.customerID = customer.Id;
dest.Added = DateTime.UtcNow;
}))
var id = await _repository.AddCustomerPackageAsync(customerPackage);
return await Task.FromResult(id);
}
然后:
public async Task<int> AddCustomerOrderAsync
public async Task<int> AddCustomerAddressAsync
.....
我考虑过要编写一种通用方法以用于上述方法,例如:
private async Task<int> Add<T, TResult>(Guid customerId, T dto) where TResult : CustomerBase
{
var customer = await GetClientFromRepositoryAsync(customerId);
var entity = _mapper.Map<TResult>(dto, options =>
{
options.AfterMap((o, customerBase) => customerBase.Id = customer.Id);
});
// Inject here different _repository methods
// var id = async _repository.Add....
return await Task.FromResult(id);
}
我想在其中注入不同的存储库方法,例如:
_repository.AddCustomerOrderAsync(clientOrder);
或
_repository.AddCustomerPackageAsync(customerPackage);
如何重构通用方法以实现目标? 有可能做到吗? 谢谢
答案 0 :(得分:2)
该实现如何?:
role_users
并像这样调用它:
private async Task<int> Add<T, TResult>(Guid customerId, T dto, Func<TResult, Task<int>> addToRepo) where TResult : CustomerBase
{
var customer = await GetClientFromRepositoryAsync(customerId);
var entity = _mapper.Map<TResult>(dto, options =>
{
options.AfterMap((o, customerBase) => customerBase.Id = customer.Id);
});
// You can write it in one line - it's just to be clear about returning the id.
var id = await addToRepo(entity);
return id;
}
也许您需要明确指定泛型。
我认为这就是@ Biesi Grr想要告诉你的。