Skip to content

Instantly share code, notes, and snippets.

@tintoy
Created January 9, 2019 10:17
Show Gist options
  • Save tintoy/eb4cfb5ecbc2b61dc2e589b1df3c0b5f to your computer and use it in GitHub Desktop.
Save tintoy/eb4cfb5ecbc2b61dc2e589b1df3c0b5f to your computer and use it in GitHub Desktop.
Microsoft.Extensions.DependencyInjection support for Hangfire
using Microsoft.Extensions.DependencyInjection;
using Hangfire;
using System;
public class DependencyInjectionActivator
: JobActivator
{
readonly IServiceProvider _serviceProvider;
public DependencyInjectionActivator(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
throw new ArgumentNullException(nameof(serviceProvider));
_serviceProvider = serviceProvider;
}
public override JobActivatorScope BeginScope(JobActivatorContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
return new Scope(
_serviceProvider.CreateScope()
);
}
class Scope
: JobActivatorScope
{
readonly IServiceScope _serviceScope;
public Scope(IServiceScope serviceScope)
{
if (serviceScope == null)
throw new ArgumentNullException(nameof(serviceScope));
_serviceScope = serviceScope;
}
public override object Resolve(Type jobType) => _serviceScope.ServiceProvider.GetRequiredService(jobType);
public override void DisposeScope() => _serviceScope.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment