cofoundry
cofoundry copied to clipboard
BackgroundTasks: Specify account to run under
It might be good if we were able to nominate an account (e.g. system account) for background tasks to run under. This is useful for tasks that use Cofoundry queries or commands which would otherwise need to be run with elevated privalidges.
Here's an example of what currently needs to be done:
using Cofoundry.Core.BackgroundTasks;
using Cofoundry.Domain;
using Cofoundry.Domain.CQS;
public class ProductAddingBackgroundTask : IAsyncRecurringBackgroundTask
{
private readonly ICommandExecutor _commandExecutor;
private readonly IExecutionContextFactory _executionContextFactory;
public ProductAddingBackgroundTask(
ICommandExecutor commandExecutor,
IExecutionContextFactory executionContextFactory
)
{
_commandExecutor = commandExecutor;
_executionContextFactory = executionContextFactory;
}
public async Task ExecuteAsync()
{
var title = Guid.NewGuid();
var command = new AddCustomEntityCommand()
{
CustomEntityDefinitionCode = ProductCustomEntityDefinition.DefinitionCode,
Title = title.ToString(),
Model = new ProductDataModel() { Description = "Description of " + title },
Publish = true
};
var elevatedExecutionContext = await _executionContextFactory.CreateSystemUserExecutionContextAsync();
await _commandExecutor.ExecuteAsync(command, elevatedExecutionContext);
}
}