Hangfiredependency injection生命周期范围

我正在重写整个问题因为我意识到原因,但仍然需要一个解决方案:

我在Hangfire中有一个经常性的工作,每分钟运行并检查数据库,可能更新一些东西,然后退出。

我将dbcontext注入包含job方法的类中。 我注册这个dbcontext以使用以下注入

builder.RegisterType().As().InstancePerLifetimeScope(); 

但是,每次作业运行时,Hangfire似乎都不会创建单独的生命周期范围,因为构造函数只会被调用一次,尽管每分钟调用一次作业方法。

这给我带来了问题。 如果用户更新了数据库中的某些值(dbcontext被注入其他地方并用于更新值),则仍在使用上下文Hangfire开始返回已更改的过时值。

Hangfire当前为每个Worker使用共享的JobActivator实例,它们使用以下方法来解析依赖关系:

  public override object ActivateJob(Type jobType) 

计划为Milestone 2.0.0的此方法添加JobActivationContext。

目前,没有办法说出依赖项得到解决的工作。 我可以想到解决这个问题的唯一方法是使用作业在不同线程上运行串行的事实(我不知道AutoFac所以我以Unity为例)。

您可以创建一个JobActivator ,它可以为每个线程存储单独的范围:

 public class UnityJobActivator : JobActivator { [ThreadStatic] private static IUnityContainer childContainer; public UnityJobActivator(IUnityContainer container) { // Register dependencies container.RegisterType(new HierarchicalLifetimeManager()); Container = container; } public IUnityContainer Container { get; set; } public override object ActivateJob(Type jobType) { return childContainer.Resolve(jobType); } public void CreateChildContainer() { childContainer = Container.CreateChildContainer(); } public void DisposeChildContainer() { childContainer.Dispose(); childContainer = null; } } 

使用带有IServerFilter实现的JobFilter为每个作业(线程)设置此作用域:

 public class ChildContainerPerJobFilterAttribute : JobFilterAttribute, IServerFilter { public ChildContainerPerJobFilterAttribute(UnityJobActivator unityJobActivator) { UnityJobActivator = unityJobActivator; } public UnityJobActivator UnityJobActivator { get; set; } public void OnPerformed(PerformedContext filterContext) { UnityJobActivator.DisposeChildContainer(); } public void OnPerforming(PerformingContext filterContext) { UnityJobActivator.CreateChildContainer(); } } 

最后设置您的DI:

 UnityJobActivator unityJobActivator = new UnityJobActivator(new UnityContainer()); JobActivator.Current = unityJobActivator; GlobalJobFilters.Filters.Add(new ChildContainerPerJobFilterAttribute(unityJobActivator)); 

我们在Hangfire.Autofac中创建了一个新的拉取请求,其中包含Dresel描述的工作。 希望它在主分支中合并:

https://github.com/HangfireIO/Hangfire.Autofac/pull/4

编辑:使用Autofac,.NET 4.5和Hangfire> = 1.5.0,使用Hangfire.Autofac nuget包 ( github )。

使用.NET 4.0(Autofac 3.5.2和Hangfire 1.1.1),我们使用Autofac设置Dresel的解决方案。 唯一的区别在于JobActivator:

 using System; using Autofac; using Hangfire; namespace MyApp.DependencyInjection { public class ContainerJobActivator : JobActivator { [ThreadStatic] private static ILifetimeScope _jobScope; private readonly IContainer _container; public ContainerJobActivator(IContainer container) { _container = container; } public void BeginJobScope() { _jobScope = _container.BeginLifetimeScope(); } public void DisposeJobScope() { _jobScope.Dispose(); _jobScope = null; } public override object ActivateJob(Type type) { return _jobScope.Resolve(type); } } } 

为了解决这个问题,我创建了一个一次性JobContext类,它有一个ILifetimeScope,当Hangfire完成作业时将会处理它。 真正的工作是通过反思来调用的。

 public class JobContext : IDisposable { public ILifetimeScope Scope { get; set; } public void Execute(string methodName, params object[] args) { var instance = Scope.Resolve(); var methodInfo = typeof(T).GetMethod(methodName); ConvertParameters(methodInfo, args); methodInfo.Invoke(instance, args); } private void ConvertParameters(MethodInfo targetMethod, object[] args) { var methodParams = targetMethod.GetParameters(); for (int i = 0; i < methodParams.Length && i < args.Length; i++) { if (args[i] == null) continue; if (!methodParams[i].ParameterType.IsInstanceOfType(args[i])) { // try convert args[i] = args[i].ConvertType(methodParams[i].ParameterType); } } } void IDisposable.Dispose() { if (Scope != null) Scope.Dispose(); Scope = null; } } 

有一个JobActivator将检查操作并在必要时创建LifetimeScope。

 public class ContainerJobActivator : JobActivator { private readonly IContainer _container; private static readonly string JobContextGenericTypeName = typeof(JobContext<>).ToString(); public ContainerJobActivator(IContainer container) { _container = container; } public override object ActivateJob(Type type) { if (type.IsGenericType && type.GetGenericTypeDefinition().ToString() == JobContextGenericTypeName) { var scope = _container.BeginLifetimeScope(); var context = Activator.CreateInstance(type); var propertyInfo = type.GetProperty("Scope"); propertyInfo.SetValue(context, scope); return context; } return _container.Resolve(type); } } 

为了帮助创建作业,不使用字符串参数,另一个类具有一些扩展。

 public static class JobHelper { public static object ConvertType(this object value, Type destinationType) { var sourceType = value.GetType(); TypeConverter converter = TypeDescriptor.GetConverter(sourceType); if (converter.CanConvertTo(destinationType)) { return converter.ConvertTo(value, destinationType); } converter = TypeDescriptor.GetConverter(destinationType); if (converter.CanConvertFrom(sourceType)) { return converter.ConvertFrom(value); } throw new Exception(string.Format("Cant convert value '{0}' or type {1} to destination type {2}", value, sourceType.Name, destinationType.Name)); } public static Job CreateJob(Expression> expression, params object[] args) { MethodCallExpression outermostExpression = expression.Body as MethodCallExpression; var methodName = outermostExpression.Method.Name; return Job.FromExpression>(ctx => ctx.Execute(methodName, args)); } } 

所以要排队一份工作,例如使用以下签名:

 public class ResidentUploadService { public void Load(string fileName) { //... } 

创建作业的代码看起来像

  var localFileName = "Somefile.txt"; var job = ContainerJobActivator .CreateJob(service => service.Load(localFileName), localFileName); var state = new EnqueuedState("queuename"); var client = new BackgroundJobClient(); client.Create(job,state); 

自hangfire.autofac 2.2.0起,支持开箱即用的解决方案。

在您的情况下,您的依赖项是在每个生命周期范围内注册的,您应该能够在设置hangfire.autofac时使用未标记的范围 。 从链接:

 GlobalConfiguration.Configuration.UseAutofacActivator(builder.Build(), false); 
Interesting Posts