Skip to content

Conversation

@lukevp
Copy link

@lukevp lukevp commented Jul 1, 2019

Add notes based on my testing with Redis.StackExchange at https://github.com/marcoCasamento/Hangfire.Redis.StackExchange and MemoryStorage.  Add gotcha about ASP.NET Core DI unable to inject PerformContext into the constructor.

**NOTE**: Like `IJobCancellationToken`, `PerformContext` is a special argument type which Hangfire will substitute automatically. You should pass `null` when enqueuing a job.
**NOTE**: Like `IJobCancellationToken`, `PerformContext` is a special argument type which Hangfire will substitute automatically. You should pass `null` when enqueuing a job. It is not currently possible to use constructor injection for the PerformContext in ASP.NET Core.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can actually do that with a custom job activator:

public class InjectContextJobActivator : JobActivator
{
    private readonly IServiceScopeFactory _scopeFactory;
    
    public InjectContextJobActivator(IServiceScopeFactory scopeFactory)
    {
        _scopeFactory = scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory));
    }

    public override JobActivatorScope BeginScope(PerformContext context)
    {
        return new Scope(context, _scopeFactory.CreateScope());
    }

    private class Scope : JobActivatorScope, IServiceProvider
    {
        private readonly PerformContext _context;
        private readonly IServiceScope _scope;

        public Scope(PerformContext context, IServiceScope scope)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _scope = scope ?? throw new ArgumentNullException(nameof(scope));
        }
        
        public override object Resolve(Type type)
        {
            return ActivatorUtilities.GetServiceOrCreateInstance(this, type);
        }

        object IServiceProvider.GetService(Type serviceType)
        {
            if (serviceType == typeof(PerformContext))
                return _context;
            return _scope.ServiceProvider.GetService(serviceType);
        }
    }
}

Just register it as a service in ConfigureServices:

services.AddSingleton<JobActivator, InjectContextJobActivator>();

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for future readers that have copied this code basically blindly, i just found out that because the serviceScope is not disposed this will cause a memory leak and possible myriad of other issues if your transient/scoped services are not cleaned up properly.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I.e. add:

/// <inheritdoc />
public override void DisposeScope()
{
    _scope.Dispose();
}


- **Provider-agnostic**: (allegedly) works with any job storage provider (currently tested with SqlServer and MongoDB).
- **Provider-agnostic**: (allegedly) works with any job storage provider (currently tested with SqlServer, MemoryStorage, Redis.StackExchange and MongoDB).
- **100% Safe**: no Hangfire-managed data (e.g. jobs, states) is ever updated, hence there's no risk to corrupt it.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe there were some issues with MemoryStorage due to incorrect implementation of Set related API. Was it fixed already?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants