When you need a temporary storage, the Memory storage is a perfect choice. In this tutorial, you will discover:
You can download the example code used in this topic on GitHub.
Memory storage is a quick way to store a small amount of data. The Memory storage isolates data by browser tab.
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.
To use the Memory storage, you first need to create a singleton/scoped service, then you will inject this service to components to use.
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.
Program.csbuilder.Services.AddScoped<MemoryStorageUtility>();
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();
}
}