Persisting data

Hi, even after a couple of years I still feel like a beginner on many subjects.

The services I’ve written use a set of data that is completely static but must be read preferably only once because reading it every time makes the call last 10 seconds longer. I thought of doing this by putting it all in a static class and passing it to the library calls each time I need it, something like:

public partial class CRMServices : Service
{
    static CRMDataClassesC.GeneralDataClasses.CRMStaticData ST;
	
	public object Get(CRMRequestTest request)
    {
        CRMLib crml;
        crml = new CRMLib(.....)
        {
            CollOfCRMStaticData = ST
        };

        ST = crml.CollOfCRMStaticData;
		
		/// DO STUFF
		
        return new CRMResponseTest
        {
			/// return stuff
        };
	}			
}

And while this works, as the first call to the endpoint caches the data, and that data is available to everyone, eventually the data (probably the cache) expires after some time…

What am I doing wrong, or is there a better way of doing things?

thanks for every helpful answer

If you always want the data loaded on Startup and always cached, I would load & register it on Startup, e.g:

public override void Configure(Container container)
{
    container.AddSingleton<IDbConnectionFactory>(
        new OrmLiteConnectionFactory(connString, SqliteDialect.Provider)); 

    using var db = container.Resolve<IDbConnectionFactory>().Open();
    container.AddSingleton(new AppData {
        Data = db.Select<Table>()
    });
}

Which your Services would use like a normal dependency, e.g:

public partial class CRMServices : Service
{
    public AppData AppData { get; set: }
}

If this doesn’t help, can you clarify exactly what you’re trying to achieve? i.e. what are issues with the current solution you’re trying to improve on?

What I’m trying to achieve is the following: I provide a data connection thin client through servicestack with a Microsoft Dynamics CRM in the backend. As we don’t want to expose the CRM organization service to the outside, and also hide the complexity of it through a thin client, the Servicestack sits in the middle providing an easy interface to the CRM backend. Some of the served CRM data is completely static. In other words, I want that subset of CRM data to be readily available in the servicestack, to optimize the connection to MS CRM. So the Servicestack should ideally at initialization make a connection to MS CRM, import the static data, and after that combine that static data with the normal fetched data at every request.

Then I would follow my above the approach, i.e. populate & register a singleton class on Startup that any Service that needs it can access like a normal dependency.