如何将服务注入工作和设置IOC容器配置?

发布于 2025-02-11 12:03:51 字数 2763 浏览 2 评论 0原文

我设置了一个作业,其中我从serviceCollection中注入了服务。问题在于,该作业(执行方法)无法运行,尽管在注入任何服务之前,它都可以正常工作。

我认为问题源于依赖性注入生命周期,因为当我将所有生命的时间更改为singleton时,作业就会发射。由于dbContext应该是瞬态我必须以另一种方式解决它。


statup.cs:

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddDbContext<EFDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Cnn")).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking), ServiceLifetime.Transient);
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            services.AddTransient<CheckTransactionConfirmJob>();
            services.AddTransient<CheckPaymentConfirmationScheduler>();

            services.AddTransient<IPaymentRepository, EfPlanRepository>();
            
        }

PaymentsVice.cs:

        private async Task RunPaymentCheckerJob(Payment payment, Guid userId,
            CheckPaymentConfirmationScheduler scheduler)
        {
            IJobDetail job = JobBuilder.Create<CheckTransactionConfirmJob>()
                .WithIdentity(Guid.NewGuid().ToString(), "CheckConfirmationJob")
                .UsingJobData("paymentId", payment.Id)
                .UsingJobData("userId", userId)
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity(Guid.NewGuid().ToString(), "CheckConfirmationGroup")
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(20)
                    .WithRepeatCount(12))
                .ForJob(job)
                .Build();
            await scheduler.GetScheduler().ScheduleJob(job, trigger);
        }

checkTransactionConfirmjob.cs

public class CheckTransactionConfirmJob : IJob
    {
        private readonly IPaymentRepository _paymentRepository;
        private readonly IServiceProvider _provider;

        public CheckTransactionConfirmJob(IPaymentRepository paymentRepository, IServiceProvider provider)
        {
            _paymentRepository = paymentRepository;
            _provider = provider;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                /// business code
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }

    }

I set up a Job in which I injected a service from servicecollection. The problem is that this job (Execute method) could not be run although before injecting any services, it was working properly.

I think the problem stems from Dependency Injection Lifetime because when I change all lifetimes to Singleton the job is fired. For the reason that DbContext should be Transient I have to solve it in another way.

Statup.cs:

public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddDbContext<EFDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Cnn")).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking), ServiceLifetime.Transient);
            services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

            services.AddTransient<CheckTransactionConfirmJob>();
            services.AddTransient<CheckPaymentConfirmationScheduler>();

            services.AddTransient<IPaymentRepository, EfPlanRepository>();
            
        }

PaymentService.cs:

        private async Task RunPaymentCheckerJob(Payment payment, Guid userId,
            CheckPaymentConfirmationScheduler scheduler)
        {
            IJobDetail job = JobBuilder.Create<CheckTransactionConfirmJob>()
                .WithIdentity(Guid.NewGuid().ToString(), "CheckConfirmationJob")
                .UsingJobData("paymentId", payment.Id)
                .UsingJobData("userId", userId)
                .Build();

            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity(Guid.NewGuid().ToString(), "CheckConfirmationGroup")
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(20)
                    .WithRepeatCount(12))
                .ForJob(job)
                .Build();
            await scheduler.GetScheduler().ScheduleJob(job, trigger);
        }

CheckTransactionConfirmJob.cs

public class CheckTransactionConfirmJob : IJob
    {
        private readonly IPaymentRepository _paymentRepository;
        private readonly IServiceProvider _provider;

        public CheckTransactionConfirmJob(IPaymentRepository paymentRepository, IServiceProvider provider)
        {
            _paymentRepository = paymentRepository;
            _provider = provider;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                /// business code
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }

    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

站稳脚跟 2025-02-18 12:03:51

石英配有两个内置替代方案,可以通过调用usemicRosoftDependentIndentionjobfactoryusemicRosoftDependendendentionscopedjobfactory(everected)。
为了使用Microsoft依赖项UsemicRosoftDependentientIndoctionJobFactory应在configureservices方法中调用:

    services.AddQuartz(q =>
    {
        q.UseMicrosoftDependencyInjectionJobFactory();
    });

Quartz comes with two built-in alternatives for job factory which can be configured via either calling UseMicrosoftDependencyInjectionJobFactory or UseMicrosoftDependencyInjectionScopedJobFactory (deprecated).

For using Microsoft dependency UseMicrosoftDependencyInjectionJobFactory should be called in ConfigureServices method:

    services.AddQuartz(q =>
    {
        q.UseMicrosoftDependencyInjectionJobFactory();
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文