Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ Migrated to hangfire #97

Merged
merged 4 commits into from
Apr 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
- Fluent Validation
- Minimal APIs
- Specifications
- Outbox Pattern with Hangfire background processing

## DDD Principles

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,10 @@
using MediatR;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using Quartz;

namespace DDD.Infrastructure.BackgroundJobs;

[DisallowConcurrentExecution]
public class ProcessOutboxMessagesJob : IJob
public class ProcessOutboxMessagesJob
{
private readonly ApplicationDbContext _applicationDbContext;
private readonly IPublisher _publisher;
Expand All @@ -22,12 +20,12 @@ public ProcessOutboxMessagesJob(ApplicationDbContext applicationDbContext, IPubl
_dateTime = dateTime;
}

public async Task Execute(IJobExecutionContext context)
public async Task Execute(CancellationToken cancellationToken)
{
var messages = await _applicationDbContext.OutboxMessages
.Where(om => om.ProcessedOnUtc == null)
.Take(20)
.ToListAsync(context.CancellationToken);
.ToListAsync(cancellationToken);

if (messages.Count == 0)
return;
Expand All @@ -42,11 +40,11 @@ public async Task Execute(IJobExecutionContext context)
continue;

// NOTE: In Production, this should be wrapped in a try-catch
await _publisher.Publish(domainEvent, context.CancellationToken);
await _publisher.Publish(domainEvent, cancellationToken);

message.ProcessedOnUtc = _dateTime.Now;
}

await _applicationDbContext.SaveChangesAsync();
await _applicationDbContext.SaveChangesAsync(cancellationToken);
}
}
10 changes: 4 additions & 6 deletions src/DDD.Infrastructure/DDD.Infrastructure.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="7.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Quartz" Version="3.6.2" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.6.2" />
<PackageReference Include="Hangfire.Core" Version="1.8.*" />
<PackageReference Include="Hangfire.SqlServer" Version="1.8.*" />
<PackageReference Include="Hangfire.AspNetCore" Version="1.8.*" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="*" />
</ItemGroup>

<ItemGroup>
Expand All @@ -29,8 +31,4 @@
<EditorConfigFiles Remove="C:\Code\Personal\dotnet-ef-domain-driven-design\DDD.Infrastructure\Migrations\.editorconfig" />
</ItemGroup>

<ItemGroup>
<None Include="C:\Code\Personal\dotnet-ef-domain-driven-design\DDD.Infrastructure\Migrations\.editorconfig" />
</ItemGroup>

</Project>
38 changes: 20 additions & 18 deletions src/DDD.Infrastructure/DependencyInjection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
using DDD.Infrastructure.Persistence;
using DDD.Infrastructure.Persistence.Interceptors;
using DDD.Infrastructure.Services;
using Hangfire;
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Quartz;

namespace DDD.Infrastructure;

Expand All @@ -29,29 +30,30 @@ public static IServiceCollection AddInfrastructure(this IServiceCollection servi
services.AddScoped<DispatchDomainEventsInterceptor>();
services.AddScoped<OutboxInterceptor>();

AddQuartz(services);
AddHangfire(services, config);

return services;
}

private static void AddQuartz(IServiceCollection services)
private static void AddHangfire(IServiceCollection services, IConfiguration config)
{
services.AddQuartz(configure =>
{
var jobKey = new JobKey(nameof(ProcessOutboxMessagesJob));

configure
.AddJob<ProcessOutboxMessagesJob>(jobKey)
.AddTrigger(trigger =>
trigger.ForJob(jobKey)
.WithSimpleSchedule(schedule =>
schedule.WithIntervalInSeconds(10)
.RepeatForever()));

configure.UseMicrosoftDependencyInjectionJobFactory();
// Add Hangfire services.
services.AddHangfire(configuration => configuration
.SetDataCompatibilityLevel(CompatibilityLevel.Version_180)
.UseSimpleAssemblyNameTypeSerializer()
.UseRecommendedSerializerSettings()
.UseSqlServerStorage(config.GetConnectionString("DefaultConnection")));

// Add the processing server as IHostedService
services.AddHangfireServer();
}

});
public static void UseInfrastructure(this IApplicationBuilder builder)
{
// This can be viewed at {localhost}/hangfire
builder.UseHangfireDashboard();

services.AddQuartzHostedService();
var manager = builder.ApplicationServices.GetRequiredService<IRecurringJobManager>();
manager.AddOrUpdate<ProcessOutboxMessagesJob>("outbox-messages", x => x.Execute(CancellationToken.None), Cron.Minutely);
}
}
2 changes: 2 additions & 0 deletions src/DDD.WebApi/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,6 @@
app.MapProductEndpoints();
app.MapOrderEndpoints();

app.UseInfrastructure();

app.Run();
3 changes: 2 additions & 1 deletion src/DDD.WebApi/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Warning",
"Hangfire": "Information"
}
},
"AllowedHosts": "*"
Expand Down