C# Singleton WebJob静态方法需要访问DI对象

C# Singleton WebJob静态方法需要访问DI对象,c#,entity-framework-core,azure-webjobs,C#,Entity Framework Core,Azure Webjobs,我正在创建Azure webjob方法,以便对添加到数据库中的游戏进行投票 这是每分钟投票一次,而且真的需要成为唯一这样做的事情,所以我想我需要它成为一个[单身] 在我阅读的所有文档中,singleton webjob方法都被标记为静态(但我找不到任何文档说明为什么应该或必须是静态的)。我可以让函数工作,因为它不是静态的,但我想知道我是否在积累麻烦 如果将该方法设置为静态,则在启动时无法再访问直接注入类中的对象 我的问题其实是在寻找指针: singleton webjob必须是(或者应该是)静

我正在创建Azure webjob方法,以便对添加到数据库中的游戏进行投票

这是每分钟投票一次,而且真的需要成为唯一这样做的事情,所以我想我需要它成为一个[单身]

在我阅读的所有文档中,singleton webjob方法都被标记为静态(但我找不到任何文档说明为什么应该或必须是静态的)。我可以让函数工作,因为它不是静态的,但我想知道我是否在积累麻烦

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

我的问题其实是在寻找指针:

  • singleton webjob必须是(或者应该是)静态的吗?如果是,为什么
  • 在任何情况下,为了将来的参考(因为我以前已经解决过这个问题),是否有一种方法可以直接访问注入其中的类对象(从静态方法),或者我应该使整个类都是静态的(这会起作用吗)?还是
  • 是否有一种非常简单的方法来实例化我错过的DB上下文,例如使用连接字符串?同样,我必须访问Appsettings,但我已经将其构建到一个单独的类中,可以在静态方法中实例化
在本例中,主要是在DBContext中创建和传递

在我的Program class-Main中,我有:

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();
        }
    }
类程序
{
静态异步任务Main()
{
var appSettings=新的appSettings();
var builder=新主机生成器();
建筑商。使用环境(“开发”);
builder.ConfigureWebJobs(b=>
{
b、 AddAzureStorageCoreServices();
b、 AddAzureStorage();
b、 AddTimers();
});
builder.ConfigureAppConfiguration((上下文,b)=>
{
b、 SetBasePath(目录.GetCurrentDirectory())
.AddJsonFile(“appsettings.json”,可选:false,reloadOnChange:true)
.AddenEnvironmentVariables();
});
builder.ConfigureServices((上下文,服务)=>
{
appSettings.AzureWebJobsStorage=context.Configuration.GetValue(“AzureWebJobsStorage”);
appSettings.DataStoreRoot=context.Configuration.GetValue(“DataStoreRoot”);
appSettings.DefaultConnection=context.Configuration.GetValue(“DefaultConnection”);
//添加应用程序设置
services.AddSingleton(appSettings);
//添加Sql
services.AddDbContext(options=>options.UseSqlServer(appSettings.DefaultConnection));
});
builder.ConfigureLogging((上下文,b)=>
{
b、 AddConsole();
//如果“设置”中存在该键,请使用它启用应用程序洞察。
string instrumentationKey=context.Configuration[“APPINSIGHTS_instrumentationKey”];
如果(!string.IsNullOrEmpty(instrumentationKey))
{
b、 添加ApplicationInsightsWebJobs(o=>o.InstrumentationKey=InstrumentationKey);
}
});
var host=builder.Build();
使用(主机)
{
等待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);

    }
公共类函数
{
私有只读应用设置\u应用设置;
私有只读RGDbContext _context;
公共函数(AppSettings AppSettings、RGDbContext上下文)
{
_appSettings=appSettings;
_上下文=上下文;
}
私有静态int TestCount=0;
//美国公共图书馆
/// 
///此函数用于轮询要运行的游戏
///它查看数据库中尚未运行的游戏
/// 
/// 
[单身人士]
public void PollForGamesToRun([TimerTrigger(“0*****”)TimerInfo myTimer)
{
GameHandler GameHandler=新GameHandler();
Console.WriteLine($“轮询游戏UTC:{DateTime.UtcNow.ToString()}”);
Console.WriteLine($“游戏本地时间的轮询{DateTime.Now.ToString()}”);
控制台写入线(TestCount);
TestCount++;
gameHandler.CheckGameQueue(_上下文);
}
如果我将“PollForGamesToRun”设为静态,那么我就无法访问_context对象。我意识到我可以指示一个对象,但这并不简单,…而且似乎有点像一把大锤敲开螺母,特别是我已经在“main”程序中创建了一个这样简单的对象