简体   繁体   English

如何在我的 ASP.NET Core 应用程序中使用 Startup.cs 之外的服务?

[英]How can I use a service outside of Startup.cs in my ASP.NET Core Application?

I has an ASP.NET Core application that serves as a sort of "job scheduler", thus I need to have the application run a cron job for configured jobs.我有一个 ASP.NET Core 应用程序,它充当一种“作业调度程序”,因此我需要让该应用程序为配置的作业运行一个 cron 作业。 I figured out a method to do this, but unfortunately, it only works in the Startup.cs file using the IServiceCollection abstract class.我想出了一个方法来做到这一点,但不幸的是,它只适用于使用 IServiceCollection 抽象类的 Startup.cs 文件。 Due to the nature of this application, I need to be able to add a cron job in my controller when a post request is made.由于此应用程序的性质,我需要能够在发出 post 请求时在我的控制器中添加一个 cron 作业。

Here is how I am adding a cron job inside Startup.cs :这是我在Startup.cs 中添加 cron 作业的方法:

public void ConfigureServices(IServiceCollection services)
        {
                // Basic config code above here

                services.AddCronJob<CronJob>(c =>
                {
                    c.TimeZoneInfo = TimeZoneInfo.Local;
                    c.CronExpression = @"" + cronEx;
                    Console.WriteLine(c.CronExpression);
                });
            }
        }

Here is my API controller and what I am trying to do:这是我的 API 控制器以及我正在尝试做的事情:

// POST: api/Jobs
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<Job>> PostJob(Job job)
{
    _context.Job.Add(job);
    await _context.SaveChangesAsync();

    services.AddCronJob<CronJob>(c =>
    {
          c.TimeZoneInfo = TimeZoneInfo.Local;
          c.CronExpression = @"" + job.CronExpression;
    });

    return CreatedAtAction("GetJob", new { id = job.Id }, job);
}

I'm not totally sure if this is possible, but any insight would be helpful.我不完全确定这是否可行,但任何见解都会有所帮助。

First question if you need to add this cron job as new service every time.第一个问题是否需要每次都将此 cron 作业添加为新服务。

If you want to use app as scheduler then the best idea is to use IHostedService - Documentation link .如果您想将应用程序用作调度程序,那么最好的方法是使用 IHostedService- 文档链接

Here you have some example of how to use IHostedService to make simple scheduler - Scheduler example based on IHostedService这里有一些关于如何使用 IHostedService 制作简单调度程序的示例 - 基于 IHostedService 的调度程序示例

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

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