Hangfire dependency injection with .NET Core - c#

How can I use .NET Core's default dependency injection in Hangfire?
I am new to Hangfire and searching for an example which works with ASP.NET Core.

See full example on GitHub https://github.com/gonzigonz/HangfireCore-Example.
Live site at http://hangfirecore.azurewebsites.net/
Make sure you have the Core version of Hangfire:
dotnet add package Hangfire.AspNetCore
Configure your IoC by defining a JobActivator. Below is the config for use with the default asp.net core container service:
public class HangfireActivator : Hangfire.JobActivator
{
private readonly IServiceProvider _serviceProvider;
public HangfireActivator(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public override object ActivateJob(Type type)
{
return _serviceProvider.GetService(type);
}
}
Next register hangfire as a service in the Startup.ConfigureServices method:
services.AddHangfire(opt =>
opt.UseSqlServerStorage("Your Hangfire Connection string"));
Configure hangfire in the Startup.Configure method. In relationship to your question, the key is to configure hangfire to use the new HangfireActivator we just defined above. To do so you will have to provide hangfire with the IServiceProvider and this can be achieved by just adding it to the list of parameters for the Configure method. At runtime, DI will providing this service for you:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IServiceProvider serviceProvider)
{
...
// Configure hangfire to use the new JobActivator we defined.
GlobalConfiguration.Configuration
.UseActivator(new HangfireActivator(serviceProvider));
// The rest of the hangfire config as usual.
app.UseHangfireServer();
app.UseHangfireDashboard();
}
When you enqueue a job, use the registered type which usually is your interface. Don't use a concrete type unless you registered it that way. You must use the type registered with your IoC else Hangfire won't find it.
For Example say you've registered the following services:
services.AddScoped<DbManager>();
services.AddScoped<IMyService, MyService>();
Then you could enqueue DbManager with an instantiated version of the class:
BackgroundJob.Enqueue(() => dbManager.DoSomething());
However you could not do the same with MyService. Enqueuing with an instantiated version would fail because DI would fail as only the interface is registered. In this case you would enqueue like this:
BackgroundJob.Enqueue<IMyService>( ms => ms.DoSomething());

DoritoBandito's answer is incomplete or deprecated.
public class EmailSender {
public EmailSender(IDbContext dbContext, IEmailService emailService)
{
_dbContext = dbContext;
_emailService = emailService;
}
}
Register services:
services.AddTransient<IDbContext, TestDbContext>();
services.AddTransient<IEmailService, EmailService>();
Enqueue:
BackgroundJob.Enqueue<EmailSender>(x => x.Send(13, "Hello!"));
Source:
http://docs.hangfire.io/en/latest/background-methods/passing-dependencies.html

Note: if you want a full sample, see my blog post on this.
All of the answers in this thread are wrong/incomplete/outdated. Here's an example with ASP.NET Core 3.1 and Hangfire.AspnetCore 1.7.
Client:
//...
using Hangfire;
// ...
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
//...
services.AddHangfire(config =>
{
// configure hangfire per your requirements
});
}
}
public class SomeController : ControllerBase
{
private readonly IBackgroundJobClient _backgroundJobClient;
public SomeController(IBackgroundJobClient backgroundJobClient)
{
_backgroundJobClient = backgroundJobClient;
}
[HttpPost("some-route")]
public IActionResult Schedule([FromBody] SomeModel model)
{
_backgroundJobClient.Schedule<SomeClass>(s => s.Execute(model));
}
}
Server (same or different application):
{
//...
services.AddScoped<ISomeDependency, SomeDependency>();
services.AddHangfire(hangfireConfiguration =>
{
// configure hangfire with the same backing storage as your client
});
services.AddHangfireServer();
}
public interface ISomeDependency { }
public class SomeDependency : ISomeDependency { }
public class SomeClass
{
private readonly ISomeDependency _someDependency;
public SomeClass(ISomeDependency someDependency)
{
_someDependency = someDependency;
}
// the function scheduled in SomeController
public void Execute(SomeModel someModel)
{
}
}

As far as I am aware, you can use .net cores dependency injection the same as you would for any other service.
You can use a service which contains the jobs to be executed, which can be executed like so
var jobId = BackgroundJob.Enqueue(x => x.SomeTask(passParamIfYouWish));
Here is an example of the Job Service class
public class JobService : IJobService
{
private IClientService _clientService;
private INodeServices _nodeServices;
//Constructor
public JobService(IClientService clientService, INodeServices nodeServices)
{
_clientService = clientService;
_nodeServices = nodeServices;
}
//Some task to execute
public async Task SomeTask(Guid subject)
{
// Do some job here
Client client = _clientService.FindUserBySubject(subject);
}
}
And in your projects Startup.cs you can add a dependency as normal
services.AddTransient< IClientService, ClientService>();
Not sure this answers your question or not

Currently, Hangfire is deeply integrated with Asp.Net Core. Install Hangfire.AspNetCore to set up the dashboard and DI integration automatically. Then, you just need to define your dependencies using ASP.NET core as always.

If you are trying to quickly set up Hangfire with ASP.NET Core (tested in ASP.NET Core 2.2) you can also use Hangfire.MemoryStorage. All the configuration can be performed in Startup.cs:
using Hangfire;
using Hangfire.MemoryStorage;
public void ConfigureServices(IServiceCollection services)
{
services.AddHangfire(opt => opt.UseMemoryStorage());
JobStorage.Current = new MemoryStorage();
}
protected void StartHangFireJobs(IApplicationBuilder app, IServiceProvider serviceProvider)
{
app.UseHangfireServer();
app.UseHangfireDashboard();
//TODO: move cron expressions to appsettings.json
RecurringJob.AddOrUpdate<SomeJobService>(
x => x.DoWork(),
"* * * * *");
RecurringJob.AddOrUpdate<OtherJobService>(
x => x.DoWork(),
"0 */2 * * *");
}
public void Configure(IApplicationBuilder app, IServiceProvider serviceProvider)
{
StartHangFireJobs(app, serviceProvider)
}
Of course, everything is store in memory and it is lost once the application pool is recycled, but it is a quick way to see that everything works as expected with minimal configuration.
To switch to SQL Server database persistence, you should install Hangfire.SqlServer package and simply configure it instead of the memory storage:
services.AddHangfire(opt => opt.UseSqlServerStorage(Configuration.GetConnectionString("Default")));

I had to start HangFire in main function. This is how I solved it:
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var serviceScope = host.Services.CreateScope())
{
var services = serviceScope.ServiceProvider;
try
{
var liveDataHelper = services.GetRequiredService<ILiveDataHelper>();
var justInitHangfire = services.GetRequiredService<IBackgroundJobClient>();
//This was causing an exception (HangFire is not initialized)
RecurringJob.AddOrUpdate(() => liveDataHelper.RePopulateAllConfigDataAsync(), Cron.Daily());
// Use the context here
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Can't start " + nameof(LiveDataHelper));
}
}
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}

Actually there is an easy way for dependency injection based job registration.
You just need to use the following code in your Startup:
public class Startup {
public void Configure(IApplicationBuilder app)
{
var factory = app.ApplicationServices
.GetService<IServiceScopeFactory>();
GlobalConfiguration.Configuration.UseActivator(
new Hangfire.AspNetCore.AspNetCoreJobActivator(factory));
}
}
However i personally wanted a job self registration including on demand jobs (recurring jobs which are never executed, except by manual trigger on hangfire dashboard), which was a little more complex then just that. I was (for example) facing issues with the job service activation, which is why i decided to share most of my implementation code.
//I wanted an interface to declare my jobs, including the job Id.
public interface IBackgroundJob {
string Id { get; set; }
void Invoke();
}
//I wanted to retrieve the jobs by id. Heres my extension method for that:
public static IBackgroundJob GetJob(
this IServiceProvider provider,
string jobId) => provider
.GetServices<IBackgroundJob>()
.SingleOrDefault(j => j.Id == jobId);
//Now i needed an invoker for these jobs.
//The invoker is basically an example of a dependency injected hangfire job.
internal class JobInvoker {
public JobInvoker(IServiceScopeFactory factory) {
Factory = factory;
}
public IServiceScopeFactory Factory { get; }
public void Invoke(string jobId)
{
//hangfire jobs should always be executed within their own scope.
//The default AspNetCoreJobActivator should technically already do that.
//Lets just say i have trust issues.
using (var scope = Factory.CreateScope())
{
scope.ServiceProvider
.GetJob(jobId)?
.Invoke();
}
}
//Now i needed to tell hangfire to use these jobs.
//Reminder: The serviceProvider is in IApplicationBuilder.ApplicationServices
public static void RegisterJobs(IServiceProvider serviceProvider) {
var factory = serviceProvider.GetService();
GlobalConfiguration.Configuration.UseActivator(new Hangfire.AspNetCore.AspNetCoreJobActivator(factory));
var manager = serviceProvider.GetService<IRecurringJobManager>();
var config = serviceProvider.GetService<IConfiguration>();
var jobs = serviceProvider.GetServices<IBackgroundJob>();
foreach (var job in jobs) {
var jobConfig = config.GetJobConfig(job.Id);
var schedule = jobConfig?.Schedule; //this is a cron expression
if (String.IsNullOrWhiteSpace(schedule))
schedule = Cron.Never(); //this is an on demand job only!
manager.AddOrUpdate(
recurringJobId: job.Id,
job: GetJob(job.Id),
cronExpression: schedule);
}
//and last but not least...
//My Method for creating the hangfire job with injected job id
private static Job GetJob(string jobId)
{
var type = typeof(JobInvoker);
var method = type.GetMethod("Invoke");
return new Job(
type: type,
method: method,
args: jobId);
}
Using the above code i was able to create hangfire job services with full dependency injection support. Hope it helps someone.

Use the below code for Hangfire configuration
using eForms.Core;
using Hangfire;
using Hangfire.SqlServer;
using System;
using System.ComponentModel;
using System.Web.Hosting;
namespace eForms.AdminPanel.Jobs
{
public class JobManager : IJobManager, IRegisteredObject
{
public static readonly JobManager Instance = new JobManager();
//private static readonly TimeSpan ZeroTimespan = new TimeSpan(0, 0, 10);
private static readonly object _lockObject = new Object();
private bool _started;
private BackgroundJobServer _backgroundJobServer;
private JobManager()
{
}
public int Schedule(JobInfo whatToDo)
{
int result = 0;
if (!whatToDo.IsRecurring)
{
if (whatToDo.Delay == TimeSpan.Zero)
int.TryParse(BackgroundJob.Enqueue(() => Run(whatToDo.JobId, whatToDo.JobType.AssemblyQualifiedName)), out result);
else
int.TryParse(BackgroundJob.Schedule(() => Run(whatToDo.JobId, whatToDo.JobType.AssemblyQualifiedName), whatToDo.Delay), out result);
}
else
{
RecurringJob.AddOrUpdate(whatToDo.JobType.Name, () => RunRecurring(whatToDo.JobType.AssemblyQualifiedName), Cron.MinuteInterval(whatToDo.Delay.TotalMinutes.AsInt()));
}
return result;
}
[DisplayName("Id: {0}, Type: {1}")]
[HangFireYearlyExpirationTime]
public static void Run(int jobId, string jobType)
{
try
{
Type runnerType;
if (!jobType.ToType(out runnerType)) throw new Exception("Provided job has undefined type");
var runner = runnerType.CreateInstance<JobRunner>();
runner.Run(jobId);
}
catch (Exception ex)
{
throw new JobException($"Error while executing Job Id: {jobId}, Type: {jobType}", ex);
}
}
[DisplayName("{0}")]
[HangFireMinutelyExpirationTime]
public static void RunRecurring(string jobType)
{
try
{
Type runnerType;
if (!jobType.ToType(out runnerType)) throw new Exception("Provided job has undefined type");
var runner = runnerType.CreateInstance<JobRunner>();
runner.Run(0);
}
catch (Exception ex)
{
throw new JobException($"Error while executing Recurring Type: {jobType}", ex);
}
}
public void Start()
{
lock (_lockObject)
{
if (_started) return;
if (!AppConfigSettings.EnableHangFire) return;
_started = true;
HostingEnvironment.RegisterObject(this);
GlobalConfiguration.Configuration
.UseSqlServerStorage("SqlDbConnection", new SqlServerStorageOptions { PrepareSchemaIfNecessary = false })
//.UseFilter(new HangFireLogFailureAttribute())
.UseLog4NetLogProvider();
//Add infinity Expiration job filter
//GlobalJobFilters.Filters.Add(new HangFireProlongExpirationTimeAttribute());
//Hangfire comes with a retry policy that is automatically set to 10 retry and backs off over several mins
//We in the following remove this attribute and add our own custom one which adds significant backoff time
//custom logic to determine how much to back off and what to to in the case of fails
// The trick here is we can't just remove the filter as you'd expect using remove
// we first have to find it then save the Instance then remove it
try
{
object automaticRetryAttribute = null;
//Search hangfire automatic retry
foreach (var filter in GlobalJobFilters.Filters)
{
if (filter.Instance is Hangfire.AutomaticRetryAttribute)
{
// found it
automaticRetryAttribute = filter.Instance;
System.Diagnostics.Trace.TraceError("Found hangfire automatic retry");
}
}
//Remove default hangefire automaticRetryAttribute
if (automaticRetryAttribute != null)
GlobalJobFilters.Filters.Remove(automaticRetryAttribute);
//Add custom retry job filter
GlobalJobFilters.Filters.Add(new HangFireCustomAutoRetryJobFilterAttribute());
}
catch (Exception) { }
_backgroundJobServer = new BackgroundJobServer(new BackgroundJobServerOptions
{
HeartbeatInterval = new System.TimeSpan(0, 1, 0),
ServerCheckInterval = new System.TimeSpan(0, 1, 0),
SchedulePollingInterval = new System.TimeSpan(0, 1, 0)
});
}
}
public void Stop()
{
lock (_lockObject)
{
if (_backgroundJobServer != null)
{
_backgroundJobServer.Dispose();
}
HostingEnvironment.UnregisterObject(this);
}
}
void IRegisteredObject.Stop(bool immediate)
{
Stop();
}
}
}
Admin Job Manager
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
if (Core.AppConfigSettings.EnableHangFire)
{
JobManager.Instance.Start();
new SchedulePendingSmsNotifications().Schedule(new Core.JobInfo() { JobId = 0, JobType = typeof(SchedulePendingSmsNotifications), Delay = TimeSpan.FromMinutes(1), IsRecurring = true });
}
}
protected void Application_End(object sender, EventArgs e)
{
if (Core.AppConfigSettings.EnableHangFire)
{
JobManager.Instance.Stop();
}
}
}

Related

Using Scoped services within a hosted service in ASP.NET Core

I have a service that I want to share between other transient services. Right now it's not really a service, but in real life application it will. How would I share my service using dependency injection?
I added some demo code below. The SharedService should be the same object for MyTransientService1 and MyTransientService2 in the "Scope" of MyCreatorService.
The second assert fails, while this is what I'd like to accomplish.
class Program
{
static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args)
=> Host.CreateDefaultBuilder(args)
.ConfigureServices((_, services) =>
{
services.AddScoped<SharedService>();
services.AddTransient<MyTransientService1>();
services.AddTransient<MyTransientService2>();
services.AddTransient<MyCreatorService>();
services.AddHostedService<MyHostedService>();
});
}
public class SharedService
{
public Guid Id { get; set; }
}
public class MyTransientService1
{
public SharedService Shared;
public MyTransientService1(SharedService shared)
{
Shared = shared;
}
}
public class MyTransientService2
{
public SharedService Shared;
public MyTransientService2(SharedService shared)
{
Shared = shared;
}
}
public class MyCreatorService
{
public MyTransientService1 Service1;
public MyTransientService2 Service2;
public MyCreatorService(MyTransientService1 s1, MyTransientService2 s2)
{
Service1 = s1;
Service2 = s2;
}
}
public class MyHostedService : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
public MyHostedService(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
var creator1 = _serviceProvider.GetRequiredService<MyCreatorService>();
var creator2 = _serviceProvider.GetRequiredService<MyCreatorService>();
Assert.That(creator1.Service1.Shared.Id, Is.EqualTo(creator1.Service2.Shared.Id));
Assert.That(creator1.Service1.Shared.Id, Is.Not.EqualTo(creator2.Service1.Shared.Id));
return Task.CompletedTask;
}
}
If you use AddScoped, the instance will be the same within the request (for instance for a HTTP Request & Response). If you need your other services to be created everytime they are resolved, you can indeed use AddTransient, but otherwise you can also use AddScoped.
I would also suggest you bind MyHostedService in this manner (if it has anything to do with your described problem), since it seems to be providing a Singleton binding. If a scope of an outer service (one with injected dependencies) is narrower, it will hold hostage injected dependencies. A singleton service with transient dependencies will therefore make all its dependencies singleton, since the outer service will only be created once and its dependencies only resolved once.
UPDATE
After understanding the problem more clearly this should work for you (no other bindings needed):
services.AddTransient<MyCreatorService>(_ =>
{
var shared = new SharedService();
shared.Id = Guid.NewGuid();
return new MyCreatorService(
new MyTransientService1(shared),
new MyTransientService2(shared));
});
Add a constructor to the SharedService class, otherwise the Id is always 000.
Use the following code to create a different scope, so the SharedService will be initialized twice:
MyCreatorService creator1;
MyCreatorService creator2;
using (var scope1 = _serviceProvider.CreateScope())
{
creator1 = scope1.ServiceProvider.GetRequiredService<MyCreatorService>();
}
using (var scope2 = _serviceProvider.CreateScope())
{
creator2 = scope2.ServiceProvider.GetRequiredService<MyCreatorService>();
}

Logging the execution of a Hangfire RecurringJob in database?

I have set up hangfire successfully for my ASP.NET project, i.e. the 11 Hangfire tables are created in my database. I tried the following command inside the Application_Start() of my project's Global.asax:
namespace myAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start(
{
System.Diagnostics.Debug.WriteLine("Recurring job will be set up.");
RecurringJob.AddOrUpdate(
"some-id",
() => System.Diagnostics.Debug.WriteLine("Job instance started at " +
DateTime.Now)),
"*/2 * * * 1-5");
}
}
}
Sadly, inside Visual Studio's window Output > Debug I only see Reccuring job will be set up. and nothing ever after. However, a SELECT * FROM [myContext].[HangFire].[Set] shows me
Key Score Value ExpireAt
recurring-jobs 1579116240 some-id NULL
So far so good, this means that the job is indeed set up.
But how do I log inside my DB each and each time when the RecurringJob is executed? Do I assume correctly that Hangfire does not do that out of the box and I have to log it myself within the arrow-function? Or is there a more elegant way?
Question on the side: Why don't I see any output of System.Diagnostics.Debug.WriteLine within my recurring job?
References
Hangfire doesn't create tables in IIS
How to configure hangfire with ASP.NET to obtain connection string from config file?
Official hangfire.io docu on recurrent tasks
You can use SeriLog with Hangfire out of the box. Serilog comes with different sinks, e.g. Serilog.Sinks.MSSqlServer. You can configure it in startup.cs:
using Serilog;
using Serilog.Sinks.MSSqlServer;
Log.Logger = new LoggerConfiguration()
.WriteTo
.MSSqlServer(
connectionString: hangfireConnectionString,
tableName: "Logs",
autoCreateSqlTable: true
).CreateLogger();
// will display any issues with Serilog config. comment out in prod.
Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
GlobalConfiguration.Configuration
.UseSqlServerStorage(hangfireConnectionString)
.UseSerilogLogProvider();
After you schedule your job, you can log it with
Log.Information(string.Format("Hanfire Job Scheduled at {0}", DateTime.Now));
Hangfire includes a concept of job filters (similar to ASP.NET MVC's Action Filters). For your use case, you would define one that would write to your database (adjust based on your needs):
using Hangfire.Common;
using Hangfire.Server;
class LogCompletionAttribute : JobFilterAttribute, IServerFilter
{
public void OnPerforming(PerformingContext filterContext)
{
// Code here if you care when the execution **has begun**
}
public void OnPerformed(PerformedContext context)
{
// Check that the job completed successfully
if (!context.Canceled && context.Exception != null)
{
// Here you would write to your database.
// Example with entity framework:
using (var ctx = new YourDatabaseContext())
{
ctx.Something.Add(/**/);
ctx.SaveChanges();
}
}
}
}
And then apply the filter to the job method:
namespace myAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start(
{
System.Diagnostics.Debug.WriteLine("Recurring job will be set up.");
RecurringJob.AddOrUpdate("some-id", () => MyJob(), "*/2 * * * 1-5");
}
[LogCompletion]
public static void MyJob()
{
System.Diagnostics.Debug.WriteLine("Job instance started at " + DateTime.Now)
}
}
}
Docs: https://docs.hangfire.io/en/latest/extensibility/using-job-filters.html
So the cron is set to fire At every 2nd minute on every day-of-week from Monday through Friday. I assume you are waiting for the job to execute and that it is in the right window of time.
Most of the references that I found on the web indicated that you can do.
RecurringJob.AddOrUpdate(() => Console.WriteLine("This job will execute once in every minute"), Cron.Minutely);
Maybe you have to line up the dots a bit better to write to the vs console.
There is also an admin portal that can be configured to see what is begin run and when.
I have the following setup.
Global.asax.cs
protected void Application_Start()
{
HangfireJobsConfig.Register();
}
public class HangfireJobsConfig
{
public static void Register()
{
if (App1Config.RunHangfireService)
{
JobStorage.Current = new SqlServerStorage(App1Config.DefaultConnectionStringName.Split('=').Last());
GlobalConfiguration.Configuration.UseConsole();
RecurringJob.AddOrUpdate("RunJob1", () => RunJob1(null), Cron.MinuteInterval(App1Config.RunJob1Interval));
RecurringJob.AddOrUpdate("RunJob2", () => RunJob2(null), Cron.MinuteInterval(App1Config.RunJob2Interval));
}
}
[AutomaticRetry(Attempts = 0, Order = 1)]
public static void RunJob1(PerformContext context)
{
//dostuff
}
[AutomaticRetry(Attempts = 0, Order = 2)]
public static void RunJob2(PerformContext context)
{
//do stuff
}
}
Startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
ConfigureHangFire(app);
}
public void ConfigureHangFire(IAppBuilder app)
{
if (App1Config.RunHangfireService)
{
GlobalConfiguration.Configuration.UseSqlServerStorage(
AppiConfig.DefaultConnectionStringName.Split('=').Last());
GlobalConfiguration.Configuration.UseConsole();
app.UseHangfireServer();
var options = new DashboardOptions
{
AuthorizationFilters = new[]
{
new AuthorizationFilter { Roles = "Inventory" }
}
};
app.UseHangfireDashboard("/hangfire", options);
}
}
}
The actual problem was a very trivial one, the initialization of the actual background server was missing BackgroundJobServer();. Here the fully functional code:
namespace myAPI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
string connString = ConfigurationManager.ConnectionStrings["myContext"].ToString();
Hangfire.GlobalConfiguration.Configuration.UseConsole();
Hangfire.GlobalConfiguration.Configuration.UseSqlServerStorage(connString,
new SqlServerStorageOptions {
CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
QueuePollInterval = TimeSpan.Zero,
UseRecommendedIsolationLevel = true,
UsePageLocksOnDequeue = true,
DisableGlobalLocks = true
});
var bgndJS = new BackgroundJobServer(); // <--- this is essential!
RecurringJob.AddOrUpdate("myRecurringJob", () => HangfireRecurringJob(), "*/2 * * * 1-5");
System.Diagnostics.Debug.WriteLine("---> RecurringJob 'myHangfireJob' initated.");
}
public void HangfireRecurringJob() {
System.Diagnostics.Debug.WriteLine("---> HangfireRecurringJob() executed at" + DateTime.Now);
Console.Beep(); // <-- I was really happy to hear the beep
}
}
}

Using Hub from separate class in ASP.NET Core 3

I'm working on a program where I receive data from SignalR, perform processing, and then send a SignalR message back to the client once the processing has finished. I've found a couple of resources for how to do this, but I can't quite figure out how to implement it in my project.
Here's what my code looks like:
Bootstrapping
public static void Main(string[] args)
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
List<ISystem> systems = new List<ISystem>
{
new FirstProcessingSystem(),
new SecondProcessingSystem(),
};
Processor processor = new Processor(
cancellationToken: cancellationTokenSource.Token,
systems: systems);
processor.Start();
CreateHostBuilder(args).Build().Run();
cancellationTokenSource.Cancel();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<TestHub>("/testHub");
});
}
}
TestHub.cs
public class TestHub : Hub
{
public async Task DoStuff(Work work)
{
FirstProcessingSystem.ItemsToProcess.Add(work);
}
}
Work.cs
public class Work
{
public readonly string ConnectionId;
public readonly string Data;
public Work(string connectionId, string data)
{
ConnectionId = connectionId;
Data = data;
}
}
Processor.cs
public class Processor
{
readonly CancellationToken CancellationToken;
readonly List<ISystem> Systems;
public Processor(
CancellationToken cancellationToken,
List<ISystem> systems)
{
CancellationToken = cancellationToken;
Systems = systems;
}
public void Start()
{
Task.Run(() =>
{
while (!CancellationToken.IsCancellationRequested)
{
foreach (var s in Systems)
s.Process();
}
});
}
}
Systems
public interface ISystem
{
void Process();
}
public class FirstProcessingSystem : ISystem
{
public static ConcurrentBag<Work> ItemsToProcess = new ConcurrentBag<Work>();
public void Process()
{
while (!ItemsToProcess.IsEmpty)
{
Work work;
if (ItemsToProcess.TryTake(out work))
{
// Do things...
SecondProcessingSystem.ItemsToProcess.Add(work);
}
}
}
}
public class SecondProcessingSystem : ISystem
{
public static ConcurrentBag<Work> ItemsToProcess = new ConcurrentBag<Work>();
public void Process()
{
while (!ItemsToProcess.IsEmpty)
{
Work work;
if (ItemsToProcess.TryTake(out work))
{
// Do more things...
// Hub.Send(work.ConnectionId, "Finished");
}
}
}
}
I know that I can perform the processing in the Hub and then send back the "Finished" call, but I'd like to decouple my processing from my inbound messaging that way I can add more ISystems when needed.
Can someone please with this? (Also, if someone has a better way to structure my program I'd also appreciate the feedback)
aspnet has a very powerful dependency injection system, why don't you use it? By creating your worker services without dependency injection, you'll have a hard time using anything provided by aspnet.
Since your "processing systems" seem to be long running services, you'd typically have them implement IHostedService, then create a generic service starter (taken from here):
public class BackgroundServiceStarter<T> : IHostedService where T : IHostedService
{
readonly T _backgroundService;
public BackgroundServiceStarter(T backgroundService)
{
_backgroundService = backgroundService;
}
public Task StartAsync(CancellationToken cancellationToken)
{
return _backgroundService.StartAsync(cancellationToken);
}
public Task StopAsync(CancellationToken cancellationToken)
{
return _backgroundService.StopAsync(cancellationToken);
}
}
then register them to the DI container in ConfigureServices:
// make the classes injectable
services.AddSingleton<FirstProcessingSystem>();
services.AddSingleton<SecondProcessingSystem>();
// start them up
services.AddHostedService<BackgroundServiceStarter<FirstProcessingSystem>>();
services.AddHostedService<BackgroundServiceStarter<SecondProcessingSystem>>();
Now that you got all that set up correctly, you can simply inject a reference to your signalR hub using IHubContext<TestHub> context in the constructor parameters of whatever class that needs it (as described in some of the links you posted).

Quartz.Net Dependency Injection .Net Core

In my project I have to use Quartz but I don't know what i do wrong.
JobFactory:
public class IoCJobFactory : IJobFactory
{
private readonly IServiceProvider _factory;
public IoCJobFactory(IServiceProvider factory)
{
_factory = factory;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
return _factory.GetService(bundle.JobDetail.JobType) as IJob;
}
public void ReturnJob(IJob job)
{
var disposable = job as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
QuartzExtensions:
public static class QuartzExtensions
{
public static void UseQuartz(this IApplicationBuilder app)
{
app.ApplicationServices.GetService<IScheduler>();
}
public static async void AddQuartz(this IServiceCollection services)
{
var props = new NameValueCollection
{
{"quartz.serializer.type", "json"}
};
var factory = new StdSchedulerFactory(props);
var scheduler = await factory.GetScheduler();
var jobFactory = new IoCJobFactory(services.BuildServiceProvider());
scheduler.JobFactory = jobFactory;
await scheduler.Start();
services.AddSingleton(scheduler);
}
}
And when I try run my Job (class have dependency injection) i always get Exception becouse:
_factory.GetService(bundle.JobDetail.JobType) as IJob;
is always null.
My class implement IJob and in startup.cs I add:
services.AddScoped<IJob, HelloJob>();
services.AddQuartz();
and
app.UseQuartz();
I using standard .net Core dependency injection:
using Microsoft.Extensions.DependencyInjection;
This is just a simple sample of my solution to solve IoC problem:
JobFactory.cs
public class JobFactory : IJobFactory
{
protected readonly IServiceProvider Container;
public JobFactory(IServiceProvider container)
{
Container = container;
}
public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
{
return Container.GetService(bundle.JobDetail.JobType) as IJob;
}
public void ReturnJob(IJob job)
{
(job as IDisposable)?.Dispose();
}
}
Startup.cs
public void Configure(IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IApplicationLifetime lifetime,
IServiceProvider container)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseMvc();
// the following 3 lines hook QuartzStartup into web host lifecycle
var quartz = new QuartzStartup(container);
lifetime.ApplicationStarted.Register(quartz.Start);
lifetime.ApplicationStopping.Register(quartz.Stop);
}
QuartzStartup.cs
public class QuartzStartup
{
private IScheduler _scheduler; // after Start, and until shutdown completes, references the scheduler object
private readonly IServiceProvider container;
public QuartzStartup(IServiceProvider container)
{
this.container = container;
}
// starts the scheduler, defines the jobs and the triggers
public void Start()
{
if (_scheduler != null)
{
throw new InvalidOperationException("Already started.");
}
var schedulerFactory = new StdSchedulerFactory();
_scheduler = schedulerFactory.GetScheduler().Result;
_scheduler.JobFactory = new JobFactory(container);
_scheduler.Start().Wait();
var voteJob = JobBuilder.Create<VoteJob>()
.Build();
var voteJobTrigger = TriggerBuilder.Create()
.StartNow()
.WithSimpleSchedule(s => s
.WithIntervalInSeconds(60)
.RepeatForever())
.Build();
_scheduler.ScheduleJob(voteJob, voteJobTrigger).Wait();
}
// initiates shutdown of the scheduler, and waits until jobs exit gracefully (within allotted timeout)
public void Stop()
{
if (_scheduler == null)
{
return;
}
// give running jobs 30 sec (for example) to stop gracefully
if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))
{
_scheduler = null;
}
else
{
// jobs didn't exit in timely fashion - log a warning...
}
}
}
consider that you should register your service into the container (in my case VoteJob) in advance.
I implement this based on this answer.
I hope it can be helpful.
This is how I did it in my application. Instead of adding the Scheduler to the ioc I only add the factory
services.AddTransient<IJobFactory, AspJobFactory>(
(provider) =>
{
return new AspJobFactory( provider );
} );
My job factory pretty much looks the same. Transient does not really matter as I only use this once anyway. My use Quartz extension method then is
public static void UseQuartz(this IApplicationBuilder app, Action<Quartz> configuration)
{
// Job Factory through IOC container
var jobFactory = (IJobFactory)app.ApplicationServices.GetService( typeof( IJobFactory ) );
// Set job factory
Quartz.Instance.UseJobFactory( jobFactory );
// Run configuration
configuration.Invoke( Quartz.Instance );
// Run Quartz
Quartz.Start();
}
The Quartz class is Singleton as well.
I got the same issue.
I update from
services.AddScoped<IJob, HelloJob>();
to
services.AddScoped<HelloJob>();
then it works.
_factory.GetService(bundle.JobDetail.JobType) as IJob; will not be null :)
Quartz.NET 3.1 will include official support for Microsoft DI and ASP.NET Core Hosted Services.
You can find the revisited packages as:
Quartz.Extensions.DependencyInjection - Microsoft DI integration
Quartz.AspNetCore - ASP.NET Core integration
The best resource the see the new DI integration in progress is to head to the example ASP.NET Core application.
https://www.quartz-scheduler.net/2020/07/08/quartznet-3-1-beta-1-released/

asp.net core service locator how to avoid in cosole application

I'm a little confused about how to avoid service locator when using a console application
Program
public static int Main(string[] args)
{
// Configuration
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").AddEnvironmentVariables().Build();
// DI container
var services = new ServiceCollection();
ConfigureServices(services, configuration);
var serviceProvider = services.BuildServiceProvider();
// Do I pass along the serviceProvider?
// Can resolve using locator pattern do I just use this in my classes?
// var exampleRepository = _serviceProvider.GetService<IExampleRepository>();
// Execute the correct command based on args
return CommandLineOptions.Execute(args);
}
private static void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<ApplicationDbContext>((s) => new ApplicationDbContext(configuration.GetSection("Data:DefaultConnection:ConnectionString").Value));
services.AddScoped<IExampleRepository, ExampleRepository>();
}
CommandLineOptions
public static class CommandLineOptions
{
public static int Execute(string[] args, IServiceProvider serviceProvider)
{
try
{
var app = new CommandLineApplication
{
Name = "dnx abc",
FullName = "Abc Commands",
Description = "ABC",
};
app.VersionOption("--version", PlatformServices.Default.Application.ApplicationVersion);
app.HelpOption("-?|-h|--help");
app.OnExecute(() =>
{
//ShowLogo();
app.ShowHelp();
return 2;
});
app.Command(
"task",
task=>
{
task.Name = "Task1";
task.FullName = "Task1";
task.Description = "Tasks";
task.HelpOption("-?|-h|--help");
task.OnExecute(() => { task.ShowHelp(); return 0; });
task.Command(
"task1",
data =>
{
data.FullName = "Task1 command";
data.Description = "Task1";
data.OnExecute(() =>
{
// Need to inject
var p = new Task1();
p.Process()
return 0;
});
I need to inject the IExampleRepository into the new Task1()
Task1
public class Task1
{
public Task1()
{
}
private readonly IExampleRepository _exampleRepository;
public Task1(IExampleRepository exampleRepository)
{
_exampleRepository = exampleRepository;
}
public void Process() {
....
}
So basically my understanding is that I register my dependencies, then I should be able to inject them throughout my classes. I'm not sure if I need to pass my serviceProvider down?
I believe that in MVC there is magic that happens to accomplish this. How would I go about injecting without using the service locator pattern?
Basically you don't want to have to pass IServiceProvider to any class except the bootstrapper (Startup) or factory methods/classes as this ties your classes to the specific IoC container.
What you can do is add dependencies to your CommandLineApplication class and resolve it in the Main method and from here you can start your dependency injection chain. This will work as long as you need/want to resolve all of your dependencies at once.
When you get in an situation where you only need to load a subset of it (i.e. using a different service or program logic when a certain parameter is passed), you'll need a kind of factory (a factory is a thin wrapper that creates and configures an object before passing it, in case of IoC it also resolves the dependencies).
In the factory implementation it's okay to reference the container, if necessary (you need scoped dependencies or transient resolving per object creation). You'll also need a factory if you need more than one instance of Task1.
There are two ways. For very simple factories you can use a factory method, that can be directly used while doing your IServiceCollection registrations.
services.AddTransient<Task1>();
services.AddTransient<Func<Task1>>( (serviceProvider) => {
return () => serviceProvider.GetService<Task1>();
});
then inject into your dependency.
public class MyTaskApplication
{
private readonly Func<Task> taskFactory;
public MyApplicationService(Func<Task> taskFactory)
{
this.taskFactory = taskFactory;
}
public void Run()
{
var task1 = taskFactory(); // one instance
var task2 = taskFactory(); // another instance, because its registered as Transient
}
}
If you need more complex configuration or with runtime parameter, it may make more sense to make a factory class.
public class TaskFactory : ITaskFactory
{
private readonly IServiceProvider services;
public TaskFactory(IServiceProvider services)
{
this.services = services;
}
public Task1 CreateNewTask()
{
// get default task service, which is transient as before
// so you get a new instance per call
return services.GetService<Task1>();
}
public Task1 CreateNewTask(string connectionString)
{
// i.e. when having multiple tenants and you want to
// to the task on a database which is only determined at
// runtime. connectionString is not know at compile time because
// the user may choose which one he wants to process
var dbContext = MyDbContext(connectionString);
var repository = new ExampleRepository(dbContext);
return new Task1(repository);
}
}
And the usage
public class MyTaskApplication
{
private readonly ITaskFactory taskFactory;
public MyApplicationService(ITaskFactory taskFactory)
{
this.taskFactory = taskFactory;
}
public void Run()
{
// Default instance with default connectionString from appsettings.json
var task1 = taskFactory.CreateNewTask();
// Tenant configuration you pass in as string
var task2 = taskFactory.CreateNewTask(tenantConnectionString);
}
}
This was my attempt at using your code in a test app, but I'm unsure if I'm doing this correctly.
I'm also unsure about how to pass in the connection string for the method in MyTaskApplication CreateNewTask(connectionString)
Will it need to be passed in as a property, or part of the constructor for MyTaskApplication or an alternative method?
public class Program
{
public static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddScoped<Task1>();
services.AddScoped<MyTaskApplication>();
services.AddTransient<ITaskFactory, TaskFactory>();
var serviceProvider = services.BuildServiceProvider();
var m = serviceProvider.GetService<MyTaskApplication>();
m.Run();
}
}
public class TaskFactory : ITaskFactory
{
private readonly IServiceProvider services;
public TaskFactory(IServiceProvider services)
{
this.services = services;
}
public Task1 CreateNewTask()
{
// get default task service, which is transient as before
// so you get a new instance per call
return services.GetService<Task1>();
}
public Task1 CreateNewTask(string connectionString)
{
// i.e. when having multiple tenants and you want to
// to the task on a database which is only determined at
// runtime. connectionString is not know at compile time because
// the user may choose which one he wants to process
//var dbContext = MyDbContext(connectionString);
//var repository = new ExampleRepository(dbContext);
return new Task1(connectionString);
}
}
public interface ITaskFactory
{
Task1 CreateNewTask();
Task1 CreateNewTask(string connectionString);
}
public class MyTaskApplication
{
private readonly ITaskFactory taskFactory;
private string tenantConnectionString;
public MyTaskApplication(ITaskFactory taskFactory)
{
this.taskFactory = taskFactory;
}
public void Run()
{
// Default instance with default connectionString from appsettings.json
var task1 = taskFactory.CreateNewTask();
task1.Process();
// Tenant configuration you pass in as string
var task2 = taskFactory.CreateNewTask(tenantConnectionString);
task2.Process();
Console.WriteLine("Running");
}
}
public class Task1
{
private string _repositoryText;
public Task1()
{
_repositoryText = String.Empty;
}
public Task1(string repositoryText)
{
_repositoryText = repositoryText;
}
public void Process()
{
Console.WriteLine("process: " + _repositoryText);
}
}

Categories

Resources