LazZiya / XLocalizer

Localizer package for Asp.Net Core web applications, powered by online translation and auto resource creating.
https://docs.ziyad.info
128 stars 14 forks source link

Adding option to refresh cache memory #21

Closed vitosaver closed 3 years ago

vitosaver commented 3 years ago

Hi Ziya,

Again me ;)

This time not with a bug but rather a suggestion for the useful feature.

It would be useful that there is the possibility to call a method to update/refresh cache values.

Does maybe this kind of function already exist? Is it maybe possible to get to cache object over dependency injection or something similar? If the function doesn't exist maybe u can point me in the right direction and I will be more than happy to make a pull request.

Best, Vito

vitosaver commented 3 years ago

Okay, I found out that I can use this:

ExpressMemoryCache _expressMemoryCache;

public TestModel(ExpressMemoryCache expressMemoryCache)
{
    _expressMemoryCache = expressMemoryCache;
}

and on change I can call ExpressMemoryCache.Remove<T>(string key)

but the problem that I have is now this return string.Format(_keyFormat, typeof(T).FullName, CultureInfo.CurrentCulture.Name, key);

because I can delete cache value only for the current Culture

I think it is better if you use T.CultureID but then that is under the assumption that we have XDbResource and that is wrong.

That is what I found out I hope you have some cleaner suggestion to do it :)

LazZiya commented 3 years ago

Hi Vito,

Welcome back :)

You found the first half of the solution, and below is the rest;

You can change the culture right before removing the key, and restore it back after the delete is completed. Culture switching can be done manually, or you may use the built-in CultureSwitcher class as simple as below:

ExpressMemoryCache _expressMemoryCache;

public TestModel(ExpressMemoryCache expressMemoryCache)
{
    _expressMemoryCache = expressMemoryCache;
}

public bool RemoveKey<T>(string key, string culture)
{
    using (new CultureSwitcher(culture))
    { // the culture is switched to 'culture'
        _expressMemoryCache.Remove<T>(key)
    } // original culture restored here
}

Hope this helps :) Ziya

vitosaver commented 3 years ago

Thank you Ziya, yes I ended up using your example.