Skip to content

Instantly share code, notes, and snippets.

@dcomartin
Created May 3, 2016 02:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcomartin/84f834fc8a0e37c74a388417ad31005d to your computer and use it in GitHub Desktop.
Save dcomartin/84f834fc8a0e37c74a388417ad31005d to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
using Hangfire.Common;
using MediatR;
using Microsoft.Practices.Unity;
using Newtonsoft.Json;
namespace Hangfire.Demo
{
class Program
{
static void Main(string[] args)
{
var container = new UnityContainer();
container.RegisterType<IMediator>(new InjectionFactory(x => new Mediator(type => x.Resolve(type), type => x.ResolveAll(type))));
container.RegisterType<IRequestHandler<Command, Unit>>(new InjectionFactory(x => new Handler()));
HangfireHelpers.Mediator = container.Resolve<IMediator>();
GlobalConfiguration.Configuration
.UseColouredConsoleLogProvider()
.UseSqlServerStorage("MyHangfireConnection");
JobHelper.SetSerializerSettings(new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Objects });
using (var server = new BackgroundJobServer())
{
BackgroundJob.Enqueue(() => HangfireHelpers.Send(new Command { Message = "Hello World!" }));
Console.WriteLine($"Hangfire Server started on Thread {Thread.CurrentThread.ManagedThreadId}.");
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
public static class HangfireHelpers
{
public static IMediator Mediator { private get; set; }
public static void Send(IRequest command)
{
Mediator.Send(command);
}
}
public class Command : IRequest
{
public string Message { get; set; }
}
public class Handler : IRequestHandler<Command, Unit>
{
public Unit Handle(Command command)
{
Console.WriteLine($"{command.Message} from Thread {Thread.CurrentThread.ManagedThreadId}");
return Unit.Value;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment