Base solution for your next web application
Open Closed

Hangfire Execution of GetAsync results in EntityNotFoundException #11916


User avatar
0
bsbunkley created

I'm currently working on a project using ASP Net Zero and Hangfire for scheduling tasks upon entity creation. I've encountered an issue where EntityNotFoundException is thrown during a job execution. The setup involves creating a WorkOrderRecurrence entity and then scheduling a recurring job with Hangfire. The job is supposed to fetch details of the newly created entity and perform further operations based on those details.

Here's the method used to create the entity and schedule the job:

[AbpAuthorize(AppPermissions.Pages_WorkOrderRecurrences_Create)]
        protected virtual async Task Create(CreateOrEditWorkOrderRecurrenceDto input)
        {
            var workOrderRecurrence = ObjectMapper.Map<WorkOrderRecurrence>(input);

            if (AbpSession.TenantId != null)
            {
                workOrderRecurrence.TenantId = (int?)AbpSession.TenantId;
            }

            await _workOrderRecurrenceRepository.InsertAsync(workOrderRecurrence);
            await CurrentUnitOfWork.SaveChangesAsync(); // Ensure the entity is saved and has an ID

            // Schedule the recurring job with Hangfire
            RecurringJob.AddOrUpdate(
                $"WorkOrderRecurrence_{workOrderRecurrence.Id}",
                () => _workOrderRecurrenceDomainService.Execute(workOrderRecurrence.Id, workOrderRecurrence.TenantId, workOrderRecurrence.CreatorUserId),
                workOrderRecurrence.CronExpression,
                new RecurringJobOptions
                {
                    TimeZone = TimeZoneInfo.FindSystemTimeZoneById(workOrderRecurrence.TimeZoneId),
                });
        }

Job located in a DomainService:

[UnitOfWork]             
public async Task Execute(long workOrderRecurrenceId, int? tenantId, long? userId)
{
    try
    {
        using (var uow = _unitOfWorkManager.Begin())
        {

            using (_abpSession.Use(tenantId, userId))
            {
                // Fetch the recurrence details
                var recurrence = await _workOrderRecurrenceRepository.GetAsync(workOrderRecurrenceId);

                // More repository actions
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine($"An error occurred during the execution of WorkOrderRecurrenceJob for ID: {workOrderRecurrenceId}", ex);
        throw;
    }
}

During the execution of the job, I am encountering an EntityNotFoundException. This exception seems to be thrown from _workOrderRecurrenceRepository.GetAsync(workOrderRecurrenceId).

I suspect there might be issues with how I am handling the unit of work and the session (_abpSession.Use()), but I am not certain.

Question: How should I correctly implement the unit of work and session management within this context to avoid the EntityNotFoundException? Are there best practices for structuring the Hangfire jobs in ABP to ensure the entity operations are handled correctly?


1 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Since you are using UnitOfWork in your Job, could you wrap your code as shown below ?

    using (var uow = UnitOfWorkManager.Begin())
    {
    	using (CurrentUnitOfWork.SetTenantId(tenantId))
    	{
    		// YOUR CODE HERE...
    		await uow.CompleteAsync();
    	}
    }