Gani Lastra
Gani Lastra

Reputation: 255

IDistributedCache on web API Get Method

I need some help how can I do caching below on an async call. The cache is injected, i just need to implement it inside the Task call...

 public SvcBooking(
        DbContextSMATA ctx,
        IMapper mapper,
        IDistributedCache cache)
    {
        _ctx = ctx;
        _mapper = mapper;
        _Bookings = ctx.Set<Booking>();
        _cache = cache;
    }

    #endregion

    #region Public Methods


    public async Task<IList<IDtoBooking>> GetAll()
    {

        //      _cache.GetAsync() not sure how to do this

        IList<Booking> settings = await _Bookings.ToListAsync();

        return _mapper.Map<IList<IDtoBooking>>(settings);
    }

Upvotes: 0

Views: 513

Answers (1)

Gani Lastra
Gani Lastra

Reputation: 255

Found a way to do this.. Yipee!!

public async Task<IList<Booking>> GetAll()
{

    //First assign a KEY (anything that you think of that makes
    // sense to the application and Unique)
     IList<Booking> bookings;
     byte[] bookingsInBytes= await _cache.GetAsync($"bookingsSampleKey");

    if (bookingsSampleKey== null)
     {

    bookings= await _Bookings.ToListAsync();

     //Now we are caching here, the data is saved into cache so that when a 
     //concurrent user tries to RE-query it within 60 seconds
     //, it would go to the ELSE below

     bookings= await _svcBooking.GetAll();                 

     string bookingsSerialized= JsonConvert.SerializeObject(bookings);

     bookingsInBytes= Encoding.UTF8.GetBytes(bookingsSerialized);

   await _cache.SetAsync($"bookingsSampleKey", bookingsInBytes, 
   new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = 
   TimeSpan.FromSeconds(60) });


    }
    else
    {
     //if I see some DATA already cached, I will retrieve it and return it 
     //instead of hitting the inner service   

     bookings= JsonConvert.DeserializeObject<IList<Booking>>(Encoding.UTF8.GetString(bookingsInBytes));


            }
  return bookings;
}

Upvotes: 1

Related Questions