Memory storage
When you need a temporary storage, the Memory storage is a perfect choice. In this tutorial, you will discover:
- What is Memory storage?
- Set up the base code.
- Use the Memory storage.
You can download the example code used in this topic on GitHub.
What is Memory storage?
Memory storage is a quick way to store a small amount of data. The Memory storage isolates data by browser tab.
How to access the Memory storage in the browser?
Unlike other browser storage, the Memory storage is easy to access. You need to spend a lot of time to dig through memory to find the value.
Set up the base code
To use the Memory storage, you first need to create a singleton/scoped service, then you will inject this service to components to use.
- Create a new folder. In this example, we will create a /Utils/MemoryStorageUtility.cs file.
- Create a C# class with the following base implementation:
public class MemoryStorageUtility
{
public Dictionary<string, object> Storage { get; set; } = new();
}
You can use other data type than Dictionary<string,object>
as in the example to store the data.
- Register the C# class at
Program.cs
builder.Services.AddScoped<MemoryStorageUtility>();
Use the Memory storage
You can use the built-in methods of your data type to manipulate the data in the memory. For example:
@inject MemoryStorageUtility MemoryStorageUtility
<h3>BrowserStorageDemonstrate</h3>
<form>
<label class="form-label">
Key
<input class="form-control" type="text" @bind-value="Key" />
</label>
<label class="form-label">
Value
<input class="form-control" type="text" @bind-value="Value" />
</label>
<button class="btn btn-primary" type="button" @onclick="SetValue">Set Value</button>
</form>
<div>Stored Value: @StoredValue</div>
<button class="btn btn-primary" type="button" @onclick="GetValue">Get Value</button>
<button class="btn btn-primary" type="button" @onclick="Remove">Remove Value</button>
<button class="btn btn-primary" type="button" @onclick="ClearAll">Clear All</button>
@code {
public string Key { get; set; } = "";
public string Value { get; set; } = "";
public string StoredValue { get; set; } = "";
public void SetValue()
{
MemoryStorageUtility.Storage[Key] = Value;
}
public void GetValue()
{
if (MemoryStorageUtility.Storage.TryGetValue(Key, out var value))
{
StoredValue = value.ToString()!;
}
else
{
StoredValue = "";
}
}
public void Remove()
{
MemoryStorageUtility.Storage.Remove(Key);
}
public void ClearAll()
{
MemoryStorageUtility.Storage.Clear();
}
}