首页 > 解决方案 > Singleton WebJob 静态方法需要访问 DI 对象

问题描述

我正在创建一个 Azure webjob 方法来轮询添加到数据库的游戏。

它是每分钟轮询一次,并且确实需要这样做,所以我认为我需要它是一个 [singleton]。

在我阅读的所有文档中,单例 webjob 方法都标记为静态,(但我找不到任何文档说明为什么应该或必须这样做)。我可以通过它不是静态的来使该功能工作,但我想知道我是否在存储麻烦。

如果我将方法设为静态,我将无法再访问在启动时直接注入到类中的对象。

我的问题真的是在寻找指针:

在这种情况下,主要是创建和传递 DBContext。

在我的程序类 - 主要我有这个:

class Program
{
    static async Task Main()
    {
        var appSettings = new AppSettings();
        var builder = new HostBuilder();
        builder.UseEnvironment("Development");

        builder.ConfigureWebJobs(b =>
        {
            b.AddAzureStorageCoreServices();
            b.AddAzureStorage();
            b.AddTimers();

        });

        builder.ConfigureAppConfiguration((context, b) =>
        {
            b.SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddEnvironmentVariables();
        });
        builder.ConfigureServices((context, services) =>
        {

            appSettings.AzureWebJobsStorage = context.Configuration.GetValue<string>("AzureWebJobsStorage");
            appSettings.DataStoreRoot = context.Configuration.GetValue<string>("DataStoreRoot");
            appSettings.DefaultConnection = context.Configuration.GetValue<string>("DefaultConnection");

            //Add in the AppSettings
            services.AddSingleton(appSettings);

            //Add Sql
            services.AddDbContext<RGDbContext>(options => options.UseSqlServer(appSettings.DefaultConnection));
        });

        builder.ConfigureLogging((context, b) =>
        {
            b.AddConsole();

            // If the key exists in settings, use it to enable Application Insights.
            string instrumentationKey = context.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
            if (!string.IsNullOrEmpty(instrumentationKey))
            {
                b.AddApplicationInsightsWebJobs(o => o.InstrumentationKey = instrumentationKey);
            }
        });
        var host = builder.Build();
        using (host)
        {
            await host.RunAsync();
        }
    }

Functions 类如下所示:

public class Functions
{
    private readonly AppSettings _appSettings;
    private readonly RGDbContext _context;

    public Functions(AppSettings appSettings, RGDbContext context)
    {
        _appSettings = appSettings;
        _context = context;
    }

    private static int TestCount = 0;


    // public void PollForGamesToRun

    /// <summary>
    /// This function Polls the Games to Run
    /// It looks at the Database for games that havent been run
    /// </summary>
    /// <param name="myTimer"></param>
    [Singleton]
    public void PollForGamesToRun([TimerTrigger("0 * * * * *")] TimerInfo myTimer)
    {
        GameHandler gameHandler = new GameHandler();
        Console.WriteLine($"Poll For Games UTC: {DateTime.UtcNow.ToString()}");
        Console.WriteLine($"Poll For Games Local Time {DateTime.Now.ToString()}");
        Console.WriteLine(TestCount);
        TestCount++;
        gameHandler.CheckGameQueue(_context);

    }

如果我将“PollForGamesToRun”设为静态,则无法访问 _context 对象。我意识到我可以创建一个,但这并不简单,(见这里) ......而且似乎有点像一把大锤来破解坚果,特别是因为我已经在“主”程序中如此简单地创建了一个。

标签: c#entity-framework-coreazure-webjobs

解决方案


推荐阅读