简体   繁体   中英

How to store data in a .NET Core 2.1 WebApi?

I'm developing a WebApi in .NET Core 2.1 and I need to have a shared key/value storage that can be written and read by any request received by the API.

The storage should use the application's heap and not external systems (for example a Redis cache or a flat file solution) since I have to keep C# objects which I can't serialize.

If I'm not wrong, you want to store your data in c#, like memory cache. You can use the class below.

 public class ApplicationCacheManager
        {
            private Dictionary<string, object> Data { get; set; }

            public ApplicationCacheManager()
            {
                Data = new Dictionary<string, object>();
            }

            public bool IsSet(string key)
            {
                return Data.TryGetValue(key, out var data) && data != null;
            }

            public T Get<T>(string key)
            {
                if (Data.TryGetValue(key, out var data))
                    return (T)data;

                return default(T);
            }

            public void Set<T>(string key, T data)
            {
                Data[key] = data;
            }

            public void Remove(string key)
            {
                Data.Remove(key);
            }

            public void Dispose()
            {
                if (Data != null)
                    Data = null;
            }
        }

This class should be singleton to store all data along application lifetime. register it to DI container as singleton.

services.AddSingleton<ApplicationCacheManager>();

If you want this class to be thread safe, You can change Dictinary to ConcurrentDictionary. here

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM