feat: 完成hangfire支持工作单元
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
using Hangfire.Server;
|
||||
using Volo.Abp.DependencyInjection;
|
||||
using Volo.Abp.Threading;
|
||||
using Volo.Abp.Uow;
|
||||
|
||||
namespace Yi.Framework.BackgroundWorkers.Hangfire;
|
||||
|
||||
public class UnitOfWorkHangfireFilter : IServerFilter, ISingletonDependency
|
||||
{
|
||||
private const string CurrentJobUow = "HangfireUnitOfWork";
|
||||
private readonly IUnitOfWorkManager _unitOfWorkManager;
|
||||
|
||||
public UnitOfWorkHangfireFilter(IUnitOfWorkManager unitOfWorkManager)
|
||||
{
|
||||
_unitOfWorkManager = unitOfWorkManager;
|
||||
}
|
||||
|
||||
public void OnPerforming(PerformingContext context)
|
||||
{
|
||||
var uow = _unitOfWorkManager.Begin();
|
||||
context.Items.Add(CurrentJobUow, uow);
|
||||
}
|
||||
|
||||
public void OnPerformed(PerformedContext context)
|
||||
{
|
||||
AsyncHelper.RunSync(()=>OnPerformedAsync(context));
|
||||
}
|
||||
|
||||
private async Task OnPerformedAsync(PerformedContext context)
|
||||
{
|
||||
if (context.Items.TryGetValue(CurrentJobUow, out var obj)
|
||||
&& obj is IUnitOfWork uow)
|
||||
{
|
||||
if (context.Exception == null && !uow.IsCompleted)
|
||||
{
|
||||
await uow.CompleteAsync();
|
||||
}
|
||||
else
|
||||
{
|
||||
await uow.RollbackAsync();
|
||||
}
|
||||
uow.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Hangfire;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Volo.Abp.BackgroundWorkers;
|
||||
using Volo.Abp.BackgroundWorkers.Hangfire;
|
||||
|
||||
namespace Yi.Framework.BackgroundWorkers.Hangfire;
|
||||
|
||||
[DependsOn(typeof(AbpBackgroundWorkersHangfireModule))]
|
||||
public class YiFrameworkBackgroundWorkersHangfireModule:AbpModule
|
||||
public class YiFrameworkBackgroundWorkersHangfireModule : AbpModule
|
||||
{
|
||||
public override void PreConfigureServices(ServiceConfigurationContext context)
|
||||
{
|
||||
@@ -17,13 +18,18 @@ public class YiFrameworkBackgroundWorkersHangfireModule:AbpModule
|
||||
//定时任务自动注入,Abp默认只有在Quartz才实现
|
||||
var backgroundWorkerManager = context.ServiceProvider.GetRequiredService<IBackgroundWorkerManager>();
|
||||
var works = context.ServiceProvider.GetServices<IHangfireBackgroundWorker>();
|
||||
|
||||
|
||||
foreach (var work in works)
|
||||
{
|
||||
//如果为空,默认使用服务器本地utc时间
|
||||
work.TimeZone = work.TimeZone ?? TimeZoneInfo.Local;
|
||||
work.TimeZone ??= TimeZoneInfo.Local;
|
||||
await backgroundWorkerManager.AddAsync(work);
|
||||
}
|
||||
}
|
||||
|
||||
public override void OnPreApplicationInitialization(ApplicationInitializationContext context)
|
||||
{
|
||||
var services = context.ServiceProvider;
|
||||
GlobalJobFilters.Filters.Add(services.GetRequiredService<UnitOfWorkHangfireFilter>());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user