1
votes

I need to keep several values I get from the Db, and will stay constant during session, though they may change due to the user sending a specific request. We used to do that with Session variables.

I thought to register a Singleton service, which will get some values from the Db and keep them throughout the session. So the service requires my DbContext.

The interface is simple:

interface IPhrases
{
    Task SetPhrasesForLanguage(int LanguageID);
}

The service class is similar to this:

public class LangPhrases : IPhrases
{
    private OVContext _context;
    private int _LanguageID;
    public string PageHeading { get; set; }

    public LangPhrases(OVContext context, int LanguageID)
    {
        _context = context;
        _LanguageID = LanguageID;
    }

    public Task SetPhrasesForLanguage(int LanguageID)
    {
        IQueryable<clsPhrases> lPhrases = (from p in _context.Phrases
                   where p.LangaugeId == LanguageID
                   select new clsPhrases()
                   {
                       Phrase=p.Phrase,
                       VarID=p.VarId
                   });
        //logic to get PageHeading from the lPhrases collection
    }
}

Will passing the scoped DbContext to a singleton service keep the DbContext in memory between requests?

To clarify: I am looking for a way to get these values and keep them for the session, WITHOUT keeping the DbContext in memory.

1
Will passing the scoped DbContext to a singleton service keep the DbContext in memory between requests? The scoped DbContext provided to the singleton will go out of scope between requests, which is bad. The next time SetPhrasesForLanguage is called it will fail due to disposed context. - Nkosi
This has turned into an XY problem. We need to see the bigger picture here to be able to advise you properly. - Nkosi
Could you also clarify what the 'Session' is? - M. Mennan Kara
A singleton service would be shared for all users, so you won’t be able to use that for caching the data, unless the service is able to handle multiple users. If you want to keep data through requests for a single user, then session state would probably be the way to go. Since that moves the data out of your service instance, you can make it scoped or even transient then. - poke

1 Answers

1
votes

You should use a service which is Request-Scoped and a IMemoryCache to cache the values. If you don't find the values in the cache, read them from DbContext, which should also be Request-Scoped.