0

I have created triggered AZURE webjob with .NetCore 2.2 console application(WebJob.Test.dll) and class libraryCommon.dll Class library has the singleton class to maintain the global values and referred to the console application.

In my scenario, webjob triggered every 5min and generating the token with one hour expiry date from webapi and used that token for other API calls. I am maintaining the token details in singleton instance.

So, I want to reuse the token for every 5min if token is not expired.

But, Singleton instance newly created every time when webjob triggered.

Common.dll

public sealed class SingletonAccessToken
{
    public string Token { get; set; }

    public DateTime ExpiryDateTime { get; set; }

    public bool IsTokenExpired => (this.ExpiryDateTime < DateTime.Now);

    private SingletonAccessToken() {  }

    private static readonly Lazy<SingletonAccessToken> Lazy = new Lazy<SingletonAccessToken>(() => new SingletonAccessToken());
  
    public static SingletonAccessToken Instance
    {
        get { return Lazy.Value;}
    }
 }

WebJob.Test.dll

using Common;

namespace WebJob.Test
{
    class Program
    {
       static void Main(string[] args)
       {
           AsyncContext.Run(() => ProcessSources());     
       }
        
      [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
      public async static Task ProcessSources()
      {
          if (string.IsNullOrEmpty(SingletonAccessToken.Instance.Token) || SingletonAccessToken.Instance.IsTokenExpired)
          {           
              GetToken();  // very first time token generating and maintaining the token details in singleton instance object.
              Console.WriteLine("Bearer access token generated...");
              Console.WriteLine("Access Token Expired in " + SingletonAccessToken.Instance.ExpiryDateTime);
          }
          else 
          Console.WriteLine("Access Token re-used ");
          // using generated token here to call webapi calls
        }
    }
}

WebJob triggered every 5min with below command

dotnet WebJob.Test.dll

Below screenshot is the sample WebJob folder structure

enter image description here

Please suggest me how to use singleton instance for every trigger.

Mohammad Aghazadeh
  • 2,108
  • 3
  • 9
  • 20
Sarvesh
  • 64
  • 6
  • A singleton isn't going to work since your application gets re-launched each time the trigger runs. No differently than debugging code from VS. Caching global values somewhere might be a better approach, but will be a security risk if its used for tokens. Just get a new token each time the trigger runs. – Anthony G. Oct 07 '22 at 21:58
  • @AnthonyG. Thank you for your comment. Is it possible to achieve singleton instance using continuous webjob?. – Sarvesh Oct 08 '22 at 16:50

0 Answers0