1

I have an extension to enqueue my view models pointing to an implementation of an interface IBackgroundJob

this are my extensions methods

private static readonly ActivitySource activitySource = new("MC.Hangfire.Extensions");

public static string Enqueue<T>(this T job, IBackgroundJobClient client)
{
    return client.Enqueue<IBackgroundJob<T>>(ps => ps.AddTelemetry(null).EnqueueJob(null, job, JobCancellationToken.Null));
}

public static IBackgroundJob<T> AddTelemetry<T>(this IBackgroundJob<T> job, PerformContext context)
{
    using var activity = activitySource.StartActivity($"Start Job {typeof(T).FullName} id {context.BackgroundJob.Id}", ActivityKind.Server);
    activity?.SetTag("JobId", context.BackgroundJob.Id);
    activity?.SetTag("JobJson", Newtonsoft.Json.JsonConvert.SerializeObject(job));
    activity?.SetTag("Job", Newtonsoft.Json.JsonConvert.SerializeObject(context.BackgroundJob.Job));
    return job;
}

My problem is that the EnqueueJob method is called, but the AddTelemetry method is not called before, how can I Add the telemetry information before calling all of my jobs, but in the context of the jobs, and of course not adding this code in all of my enqueue methods?

I'm looking for the Hangfire filters, but I think that there should be a way to inject the filter with the DI of the ASP.NET core application

I created this issue on github because I think that the problem with instrumentation is a little deeper in the code

https://github.com/HangfireIO/Hangfire/issues/2017

Luiz Bicalho
  • 813
  • 1
  • 12
  • 30
  • 1
    As far as I can tell, the job is already started when `AddTelemetry` is invoked. You need to rely on filters. You can instrument only methods on which you put a custom `AddTelemetry` attribute. See this answer https://stackoverflow.com/a/70334037/1236044 – jbl Mar 29 '22 at 14:57
  • I tried to use filters, but I needed to open an activity in one method and then stop the activity in another, this way I needed to use a transient filter, but the filter is singleton – Luiz Bicalho Mar 29 '22 at 20:20

0 Answers0