0

I have an IHostedService that saves a reference table from the database to cache in .NET Core 6. Meaning, the information saved will not be changed; it's just a reference table. Though there were probably multiple users who will access this, the data wont be changed and appended. For me this will be enough.

Question/s: though this is simple - are there any standard ways of doing this? (I'm just thinking the data is just plainly saved in memory). Isn't it unsafe? Any thoughts?

Start up:

builder.Services.AddMemoryCache();
builder.Services.AddHostedService<InitializeCacheService>();

To initialize it:

public class InitializeCacheService : IHostedService
{
    private readonly IServiceProvider _serviceProvider;

    public InitializeCacheService (IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        using (var scope = _serviceProvider.CreateScope())
        {
            var repo = _serviceProvider.GetService<IRepository>();
            var values = repo.GetValues();

            var cache = _serviceProvider.GetService<IMemoryCache>();

            cache.Set("ValuesList", values);
        }

        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        return Task.CompletedTask;
    }
}

To retrieve cache:

[HttpGet("{key}")]
public ActionResult<string> Get(string key)
{
    // _cache.Count is 0
    if (!_cache.TryGetValue(key, out var value))
    {
        return NotFound($"The value with the {key} is not found");
    }

    return value + "";
}

1 Answer 1

0

Good afternoon, I use this class:

    private IMemoryCache _memoryCache;

    public FabricaHub(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }

To set a cache value:

    _memoryCache.Set("key", value);

To get a cached value:

   _memoryCache.TryGetValue("key", out value);

I hope it works for you, regards

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the info @JaviFrances . Yes it'll work but my question is more of a clarification of that code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.