.NET Core控制台应用|带有依赖注入的Hangfire

问题描述

目标: 从根本上讲,我正在尝试向控制台应用程序添加一个已注入依赖项的后台作业。

问题: 尽管作业已排队,但它们从未执行。

Program.cs

var appSettings = ConfigHelper.GetConfig();
Console.WriteLine("Initialising Hangfire Server...");
GlobalConfiguration.Configuration.UsesqlServerStorage(appSettings.ConnectionString);
using (var server = new BackgroundJobServer())
{
    Console.WriteLine("Hangfire Server started.");

    var t = serviceProvider.GetService<ITestService>();
    t.test();

    Console.ReadKey();
} 

ServiceProviderFactory.cs

public static void Setup()
{
     IServiceCollection services = new ServiceCollection();

     ...
        
     services.AddDbContext<Db>(x => x.UsesqlServer(appSettings.ConnectionString));
     services.AddTransient<IInsertLogJob,InsertLogJob>();
     services.AddTransient<ITestService,TestService>();

     _serviceProvider = services.BuildServiceProvider();  
 }

TestService.cs

public interface ITestService
{
    void test();
}
public class TestService : ITestService
{
    private readonly ILogger<TestService> _logger;

    public TestService(ILogger<TestService> logger)
    {
        _logger = logger;
    }
    public void test()
    {
        logger.Log@R_666_4045@ion("Test");
        _logger.LogError("Error");
    }
}

Logger.cs

public class Logger : ILogger
{
    ...
   Log log = new Log()
            {
                Message = message,EventId = eventId.Id,ObjectId = eventId.Name,LogLevel = logLevel.ToString(),CreatedTime = DateTime.Now
            };

   BackgroundJob.Enqueue<IInsertLogJob>(j => j.Insert(log));
}

InsertLogJob.cs

public interface IInsertLogJob
{
    void Insert(Log log);
}

public class InsertLogJob : IInsertLogJob
{
    private Db _dataContext;
    public InsertLogJob(Db context)
    {
        _dataContext = context;
    }
    public void Insert(Log log)//<-- this never happens
    {
        _dataContext.Logs.Add(log);
        _dataContext.SaveChanges();
    }
}

数据库记录

Screnshot

因此,直到必须将数据插入数据库的所有代码都在运行,根据上图插入了Hangfire作业,但是从未执行过该代码

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)