Azure WebJob console application not maintaining the singleton instance object from dependency dll

145 Views Asked by At

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.

0

There are 0 best solutions below