I've got a service that loads data from a databasr and it performs almost the same operations in all methods.
private async Task GetProvenances()
{
try
{
var result = await commonRepository.GetProvenances();
if (result != null)
{
provenanceContainerService.Provenances = result;
LogTo.Information(InitCacheMessages.STR_GET_PROVENANCES, result.Count);
}
else
{
LogTo.Warning(InitCacheMessages.STR_GET_PROVENANCES_FAILED);
}
}
catch (Exception ex)
{
exceptionService.HandleException(ex);
}
}
private async Task GetPkInstrumentMarkets()
{
try
{
var result = await commonRepository.GetPkInstrumentMarkets();
if (result != null)
{
pkInstrumentMarketContainerService.PkInstrumentMarkets = result;
LogTo.Information(InitCacheMessages.STR_GET_PK_INSTRUMENT_MARKETS, result.Count);
}
else
{
LogTo.Warning(InitCacheMessages.STR_GET_PK_INSTRUMENT_MARKETS_FAILED);
}
}
catch (Exception ex)
{
exceptionService.HandleException(ex);
}
}
private async Task GetPkMotivations()
{
try
{
var result = await commonRepository.GetPkMotivations();
if (result != null)
{
pkMotivationsContainerService.PkMotivations = result;
LogTo.Information(InitCacheMessages.STR_GET_PK_MOTIVATIONS, result.Count);
}
else
{
LogTo.Warning(InitCacheMessages.STR_GET_PK_MOTIVATIONS_FAILED);
}
}
catch (Exception ex)
{
exceptionService.HandleException(ex);
}
}
How can I refactor this so I don't have to repeat the same code for about 30 methods?
UPDATE 1
Hello, I've done this way this night
protected async Task PerformInitInternal(string okMessage, string koMessage, Func<Task<IList<T>>> function)
{
try
{
var result = await function();
if (result != null)
{
Items = result;
LogTo.Information(okMessage, result.Count);
}
else
{
LogTo.Warning(koMessage);
}
isInitialized = true;
}
catch (Exception ex)
{
ExceptionService.HandleException(ex);
}
}
And I call it this way
public override Task Init()
{
return PerformInitInternal(InitCacheMessages.STR_GET_COUNTERPARTS,
InitCacheMessages.STR_GET_COUNTERPARTS_FAILED, () => CommonRepository.GetCrossSplitAsync());
}
Can this be ok?
async (commonRepository) => await commonRepository.GetProvenances())
\$\endgroup\$commonRepository
is, for example. Mind including the fields and constructor of that class? \$\endgroup\$