C#重构方法遵守DRY原理

问题描述

我有一个问题,关于如何实现一种方法以能够在其他方法中使用它而无需重复代码和遵守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);

如何重构通用方法以实现目标? 有可能做到吗? 谢谢

解决方法

该实现如何?:

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想要告诉你的。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...