How to get the PerformContext from hangfire API

5.3k views Asked by At

In our project we are using aspnetzero template. This template allows a simple but abstracted usage of hangfire. Now we would like to add Hangfire.Console to our project which would allow us to write logs to hangfires dashboard.

In order to write a log statement to the dashboard console we have to access the PerformContext of the current running job. Unfortunately because of the abstraction in aspnetzero we can't inject the PerformContext as it would be planned by hangfire. What we do have access to is the hangfire namespace and all it's static objects.

Therefore my question: Is there a way to get the PerformContext by another way than passing null to the execution method?

What I have tried so far:

  • By using the IServerFilter interface a method OnPerforming should be called. But unfortunately this is not the case within aspnetzero background jobs.
  • I tried to overwrite/extend the given base class BackgroundJob< T > of aspnetzero but with no luck. Perhaps someone can give me a hint in this direction.
2

There are 2 answers

2
Afonso Dutra Nogueira Filho On

I used JobFilterAttribute with a IServerFilter.

Example:

[AttributeUsage(AttributeTargets.Class)]
 public class HangFirePerformContextAttribute : JobFilterAttribute, IServerFilter
{
         private static PerformContext _Context;

        public static PerformContext PerformContext
        {
            get
            {
                return new PerformContext(_Context);
            }
        }
        public void OnPerformed(PerformedContext filterContext)
        {
            Context = (PerformContext)filterContext;
            _Context = Context;
        }
        public void OnPerforming(PerformingContext filterContext)
        {
            Context = (PerformContext)filterContext;
            _Context = Context;
        }
}

And I create a new Class AsyncBackgroundJobHangFire<TArgs> : AsyncBackgroundJob<TArgs>

Exemple:

    [HangFirePerformContext]
    public abstract class AsyncBackgroundJobHangFire<TArgs> : AsyncBackgroundJob<TArgs>
    {
        public PerformContext Context { get; set; }

        protected async override Task ExecuteAsync(TArgs args)
        {
            Context = HangFirePerformContextAttribute.PerformContext;
            await ExecuteAsync(args, Context);
        }

        protected abstract Task ExecuteAsync(TArgs args, PerformContext context);
    }

It´s Work

In a Class of job i use a AsyncBackgroundJobHangFire

And de method is

        [UnitOfWork]
        protected override async Task ExecuteAsync(string args, PerformContext context)
        {
        }
0
Mtaraby On

You should never use a static field for that, even if marked with a ThreadStaticAttribute , please refer to this link for more details

https://discuss.hangfire.io/t/use-hangfire-job-id-in-the-code/2621/2