在Hangfire作业中无法使用依赖注入

问题描述 投票:0回答:1

上下文

我使用Hangfire(1.7.11版)作为调度程序。但是我不能在工作中使用适当的DI。

到目前为止有效”

我有没问题安排这样的事情,因为事实SomeConcreteService具有无参数构造函数:

RecurringJob.AddOrUpdate<SomeConcreteService>(jobId, mc => Console.WriteLine($"Message from job: {mc.GetValue()}"), "1/2 * * * *");

什么不起作用

但是当我尝试使用此处推荐的内容将服务注入到Hangfire作业中时出现异常:https://docs.hangfire.io/en/latest/background-methods/using-ioc-containers.html

当我尝试使用DI添加新的计划作业时,出现以下异常:

Exception thrown: 'System.InvalidOperationException' in System.Linq.Expressions.dll: 'variable 'mc' of type 'TestHangfire.IMyContract' referenced from scope '', but it is not defined'

此行发生异常:

RecurringJob.AddOrUpdate<IMyContract>(jobId, mc => Console.WriteLine($"Message from job {jobId} => {mc.GetValue()}"), "1/2 * * * *");

这个问题是如此微不足道,以至于我确定我缺少明显的东西。

感谢您的帮助。

(几乎)完整的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Hangfire;
using Hangfire.SqlServer;
using Hangfire.Storage;
using System.Text.Json;

namespace TestHangfire
{
    #region Service
    public interface IMyContract
    {
        string GetValue();
    }
    public class MyContractImplementation : IMyContract
    {
        public string _label;

        public MyContractImplementation(string label)
        {
            _label = label;
        }

        public string GetValue() => $"{_label}:{Guid.NewGuid()}";
    }
    #endregion

    #region 2 kinds of activators
    public class ContainerJobActivator : JobActivator
    {
        private IServiceProvider _container;

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

        public override object ActivateJob(Type type)
        {
            return _container.GetService(type);
        }
    }
    public class ScopedContainerJobActivator : JobActivator
    {
        readonly IServiceScopeFactory _serviceScopeFactory;
        public ScopedContainerJobActivator(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null) throw new ArgumentNullException(nameof(serviceProvider));
            _serviceScopeFactory = serviceProvider.GetService<IServiceScopeFactory>();
        }

        public override JobActivatorScope BeginScope(JobActivatorContext context)
        {
            return new ServiceJobActivatorScope(_serviceScopeFactory.CreateScope());
        }
        private class ServiceJobActivatorScope : JobActivatorScope
        {
            readonly IServiceScope _serviceScope;
            public ServiceJobActivatorScope(IServiceScope serviceScope)
            {
                if (serviceScope == null) throw new ArgumentNullException(nameof(serviceScope));
                _serviceScope = serviceScope;
            }
            public override object Resolve(Type type)
            {
                return _serviceScope.ServiceProvider.GetService(type);
            }
        }
    }
    #endregion
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHangfire(configuration => configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseSqlServerStorage("Server=localhost,1433;Database=HangfireTest;user=sa;password=xxxxxxxxx;MultipleActiveResultSets=True", new SqlServerStorageOptions
                {
                    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                    QueuePollInterval = TimeSpan.Zero,
                    UseRecommendedIsolationLevel = true,
                    UsePageLocksOnDequeue = true,
                    DisableGlobalLocks = true
                }));

            services.AddHangfireServer();
            services.BuildServiceProvider();
            services.AddScoped<IMyContract>(i => new MyContractImplementation("blabla"));
            // doesn't work either
            // services.AddSingleton<IMyContract>(i => new MyContractImplementation("blabla"));
            // doesn't work either
            // services.AddTransient<IMyContract>(i => new MyContractImplementation("blabla"));

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider serviceProvider)
        {
            // Just to ensure the service is correctly injected...
            Console.WriteLine(serviceProvider.GetService<IMyContract>().GetValue());

            // I face the problem for both activators: ScopedContainerJobActivator or ContainerJobActivator
            GlobalConfiguration.Configuration.UseActivator(new ContainerJobActivator(serviceProvider));
            // GlobalConfiguration.Configuration.UseActivator(new ScopedContainerJobActivator(serviceProvider));

            app.UseRouting();
            app.UseHangfireDashboard();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync(JsonSerializer.Serialize(Hangfire.JobStorage.Current.GetConnection().GetRecurringJobs()
                        .Select(i => new { i.Id, i.CreatedAt, i.Cron }).ToList()));
                });
                endpoints.MapGet("/add", async context =>
                {
                    var manager = new RecurringJobManager();
                    var jobId = $"{Guid.NewGuid()}";

                    // I GET AN EXCEPTION HERE: 
                    // Exception thrown: 'System.InvalidOperationException' in System.Linq.Expressions.dll: 'variable 'mc' of type 'TestHangfire.IMyContract' referenced from scope '', but it is not defined'
                    manager.AddOrUpdate<IMyContract>(jobId, mc => Console.WriteLine($"Message from job {jobId} => {mc.GetValue()}"), "1/2 * * * *");

                    // doesn't work either: it's normal, it is just a wrapper of what is above
                    // RecurringJob.AddOrUpdate<IMyContract>(jobId, mc => Console.WriteLine($"Message from job {jobId} => {mc.GetValue()}"), "1/2 * * * *");

                    await context.Response.WriteAsync($"Schedule added: {jobId}");
                });
            });
        }
    }
}

上下文我使用Hangfire(版本1.7.11)作为调度程序。但是我不能在工作中使用适当的DI。考虑到SomeConcreteService ...

asp.net-core dependency-injection hangfire
1个回答
0
投票

我发现了问题。

© www.soinside.com 2019 - 2024. All rights reserved.