© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
10 replies
RacerDelux

Best Way To Load and Cache Scoped Data?

I am using MediatR, so scoped services essentially live the lifetime of the MediatR request.
Given that, I want to load configuration from a database if not loaded (using Entity Framework), then cache the returned data, as it is used multiple times for the request.

What is the best way to go about this? This is my current code, but this is blocking and I would think could cause performance issues.

This particular example would remove 4 round trip database calls.
public class ScopedCachingService(DbContext context)
{
    private Configurations[]? GlobalConfiguration { get; set; }

    public Configurations[] GetGlobalConfigurationAsync()
    {
        return GlobalConfiguration ??= context.Configuration.OrderBy(c => c.ConfigKey).ToArray();
    }
}
public class ScopedCachingService(DbContext context)
{
    private Configurations[]? GlobalConfiguration { get; set; }

    public Configurations[] GetGlobalConfigurationAsync()
    {
        return GlobalConfiguration ??= context.Configuration.OrderBy(c => c.ConfigKey).ToArray();
    }
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Best way to set up a websocket and API to access the data?
C#CC# / help
3y ago
✅ Scoped, Singleton and HostedService
C#CC# / help
3y ago
Best Way to store data for an Discord Bot
C#CC# / help
3y ago
❔ Best way to cache index of an object in a list
C#CC# / help
3y ago