简体   繁体   English

Hangfire 1.6.4 .NET Core - 无法解决依赖关系

[英]Hangfire 1.6.4 .NET Core - Could not resolve dependencies

I am using Hangfire 1.6.4 for my .NET Core project. 我在我的.NET Core项目中使用Hangfire 1.6.4。

Here is my Schedule controller: 这是我的Schedule控制器:

    [HttpPost]
    public void Post([FromBody]EmailSchedulerDto emailSchedulerDto)
    {
        // test only
        emailSchedulerDto = new EmailSchedulerDto
        {
            UserId = "",
            Email = "myEmail@gmail.com",
            StoresId = new List<string>(),
            CronPattern = "* * * * *"
        };
        RecurringJob.AddOrUpdate(
            () =>
                _emailScheduler.ScheduleEmail(emailSchedulerDto.UserId, emailSchedulerDto.Email,
                    emailSchedulerDto.StoresId), emailSchedulerDto.CronPattern);
    }

But I have an error during job execution: 但是我在执行作业时遇到错误:

// Job ID: #183
using MyProject.Services.Email;

var emailScheduler = Activate<EmailScheduler>();
await emailScheduler.ScheduleEmail(
    "",
    "myEmail@gmail.com",
    FromJson<IEnumerable`1>("[]")
storesId
);

System.InvalidOperationException System.InvalidOperationException

No service for type 'MyProject.Services.Email.EmailScheduler' has been registered. 没有注册“MyProject.Services.Email.EmailScheduler”类型的服务。

I've already registered ContainerJobActivator like this: 我已经注册了ContainerJobActivator:

public class ContainerJobActivator : JobActivator
{
    private readonly IServiceProvider _serviceProvider;

    public ContainerJobActivator(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public override object ActivateJob(Type type)
    {
        return _serviceProvider.GetService(type);
    }
}

And in Startup class: 在Startup类中:

GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(services.BuildServiceProvider()));

Whats wrong? 怎么了?

Thank you! 谢谢!

Here is what helped for me: 1. Register Hangfire like this: 这对我有帮助:1。像这样注册Hangfire:

services.AddHangfire(configuration => configuration
                       .UseSqlServerStorage("connection string here"));

2. And one more thing (should be first): 还有一件事(应该是第一件事):

services.AddScoped<EmailScheduler, EmailScheduler>();

I don't mark this answer as a right answer for some time... But If will not another answers, I will do) 我有一段时间没有把这个答案标记为正确的答案......但如果不是另一个答案,我会这样做)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM