I have written a client that saves files to Azure. There is an async method as follows that that I want to pass down to the repository where I want to be able to invoke the SaveFile() method inside a transaction.
My Azure file client as follows:
public async Task<bool> SaveFile(string customerId, string fileName, byte[] data)
{
try
{
var directory = await RetrieveDirectory(customerId);
var file = directory.GetFileReference(fileName);
await file.UploadFromByteArrayAsync(data, 0, data.Length);
return true;
}
catch (Exception ex)
{
_logger.LogError("Unable to save file on Azure storage for customer {0} and filename {1}. Exception {2}", customerId, fileName, ex.ToString());
}
return false;
}
From the CommandHandler I do:
if (await _translationAttachmentService.CreateTranslationAttachment(
command.CustomerId, attachment,
() => client.SaveFile(command.CustomerId.ToString(), command.FileType, command.Data)))
{
return new CommandResult<TranslationAttachment>(true, attachment);
}
The Transaction is reached by sending the callback from the CommandHandler via the Service, only calling the Repository which is below:
public async Task CreateTranslationAttachmentByTranslationIdAsync (TranslationAttachment attachment, Func<Task<bool>> callback)
{
using (var transaction = await _context.Database.BeginTransactionAsync())
{
await _context.Set<TranslationAttachment>().AddAsync(attachment);
var result = await callback();
if (result)
{
transaction.Commit();
}
else
{
transaction.Rollback();
throw new Exception("Unable to save file.");
}
}
}
When reaching the Repository method the thread jumps down straight after adding the Attachment Entity to transaction.Rollback(). I never reach the breakpoint in the SaveFile() method so I suspect I am misusing async in some way.
Many thanks in advance for any help!
Comments
Post a Comment