Created
January 9, 2019 10:17
-
-
Save tintoy/eb4cfb5ecbc2b61dc2e589b1df3c0b5f to your computer and use it in GitHub Desktop.
Microsoft.Extensions.DependencyInjection support for Hangfire
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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