question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Is there a way to overwrite existing cache belongs to a context in Polly cache?

See original GitHub issue

Summary: What are you wanting to achieve? I am new to Polly and I am using Polly to save response from API call. I am using .net standard library project. I am able to save cache. But I need to overwrite cache item after any update occurred to that resource.

What code or approach do you have so far?
This is how I configured for polly caching.

services.AddMemoryCache();
			services.AddSingleton<IAsyncCacheProvider, MemoryCacheProvider>();
			services.AddSingleton<IReadOnlyPolicyRegistry<string>, Polly.Registry.PolicyRegistry>((serviceProvider) =>
			{
				var registry = new PolicyRegistry();
				registry.Add("exchangeCachePolicy",
					Policy.CacheAsync(
						serviceProvider
							.GetRequiredService<IAsyncCacheProvider>()
							.AsyncFor<List<OutlookCategory>>(),
						new SlidingTtl(TimeSpan.FromMinutes(5))));
				return registry;
			});

I used following code to read from cache

var existingMasterCategories =  await _policyRegistry.Get<IAsyncPolicy<List<OutlookCategory>>>("exchangeCachePolicy")
													.ExecuteAsync(async context => await GetMasterCategoriesAsync(exchangeUserId), new Context($"GetOutlookMasterCategories-{exchangeUserId}"));

It is always useful to see:

  • code of any policy declarations,
  • code of the calls to .Execute/AndCapture/Async(...)

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:11 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
piyumi25commented, Jul 27, 2021
var messageWithCategory = new Message();
var outlookCategoryColor = (CategoryColor)Enum.Parse(typeof(CategoryColor), categoryColor);

// check for master categories in polly cache and get it, else call GetMasterCategoriesAsync()
var existingMasterCategories =  await _policyRegistry.Get<IAsyncPolicy<List<OutlookCategory>>>("exchangeCachePolicy")
	.ExecuteAsync(async context => await GetMasterCategoriesAsync(exchangeUserId), new Context($"GetOutlookMasterCategories-{exchangeUserId}"));

var a3SyncCategory = existingMasterCategories.FirstOrDefault(x => x.DisplayName.Equals(categoryName, StringComparison.InvariantCultureIgnoreCase));
				
if (a3SyncCategory == null)
{
	// create master category
	a3SyncCategory = await CreateMasterCategoryAsync(exchangeUserId, categoryName, outlookCategoryColor);
	//update cache
}
else
{
	//check if category has same color
	if (!a3SyncCategory.Color.Value.Equals(outlookCategoryColor))
	{
		//update category color
		a3SyncCategory = await UpdateMasterCategoryAsync(exchangeUserId,a3SyncCategory.Id, categoryName, outlookCategoryColor);
		//update cache
		var cancellationToken = new CancellationToken();
		var updatedMasterCategories = await GetMasterCategoriesAsync(exchangeUserId);
		await _cacheProvider.PutAsync(
			"exchangeCachePolicy",
			updatedMasterCategories,
			new Ttl(TimeSpan.FromMinutes(5)),
			cancellationToken,
			true);
	}
}

@martincostello Above is the part of the method I am using to integrate with polly cache

[martincostello] Edited formatting for readability

1reaction
piyumi25commented, Jul 27, 2021

Thanks @martincostello , I will try for this.

Read more comments on GitHub >

github_iconTop Results From Across the Web

[Question] How to invalidate/overwrite a cache value with ...
Hello, I am trying to invalidate a cache value but I can't see a way. My scenario is: I access the cache and...
Read more >
Polly cache policy is not adding values to the cache
I think I found the answer in the source code. In the class CacheEngine there is the following code. if (ttl.Timespan > TimeSpan....
Read more >
Using Execution Context in Polly
This precludes a dependency injection approach where you define policies centrally on startup, then provide them by DI to the point of use....
Read more >
Polly
How to Invalidate a Cache item using Polly [Add Remove and RemoveAsync to cache ... Is there a way to overwrite existing cache...
Read more >
Caching in Polly and the HttpClientFactory - no dogma blog
First let's look at how to use the Cache Policy using PolicySelector method on the HttpClientFactory to apply the policy to the request,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found