use an in memory collection in dotnet core - how to make available to all classes

50 Views Asked by At

IN dotnet core project, how do you make a collection available in memory to any class at any given time? I was thinking of the following approach:

public interface IInMemoryCache
{
    public void Setup();
}

public class InMemoryCache : IInMemoryCache
{
    private List<MyObject> cache;
    public void Setup() // entered once when app is started 
    {
        cache = new List<MyObject>() { 
                new MyObject("param1", "param2"), 
                new MyObject("param3", "param4") 
    } 
    public IList<MyObject> GetCollection() 
    {
        return this.collection;
    }
}

and then in Startup:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IInMemoryCache cache)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    cache.Setup();

etc

and also:

public void ConfigureServices(IServiceCollection services) { 
    services.AddSingleton<IInMemoryCache, InMemoryCache>();

Is this a good approach, does it mean I can inject IInMemoryCache in any class and able to access the cache object? - for the whole lifetime of the app (meaning, while it's up and running, if I restart it, the collection is expected to again initialise from running the Setup method)

So right now in any class I just add: IInMemoryCache cache and then cache.GetCollection() to retrieve the collection (that was setup ONCE at app startup).

is there a better way like a native feature for caching a collection available to all classes?

0

There are 0 best solutions below