Skip to content

4. Caching operations

Vladyslav Lobyntsev edited this page Mar 5, 2024 · 1 revision

CRUD caching operations (Create, Read, Update, Delete) are currently supported. The caching API is represented by ICache interface.

public interface ICache
{
    ValueTask CacheAsync<TEntity>(TEntity targetObject, PolicyName? policyName = null) where TEntity : class;
        
    ValueTask<TEntity?> RetrieveAsync<TEntity>(object key, PolicyName? policyName = null) where TEntity : class;
        
    ValueTask<TEntity?> RetrieveAsync<TEntity>(PolicyName? policyName = null) where TEntity : class;
        
    ValueTask RemoveAsync<TEntity>(object key, PolicyName? policyName = null) where TEntity : class;

    ValueTask RemoveAsync<TEntity>(PolicyName? policyName = null) where TEntity : class;
}

1. Create

To add new value to the cache, call

cache.CacheAsync(user);

In the case of named policies, the policy name should be passed as well.

cache.CacheAsync(user, new PolicyName("UserPolicyName"));

2. Read

To read the value from the cache, the key should be passed. If the key is a scalar (one of the entity properties), it can be used directly.

var userId = 42;
cache.RetrieveAsync<User>(userId);

In the case of a nonscalar value key (more than one of the entity properties), the key (class or struct) should contain corresponding properties with the same names as the configured entity properties.

record UserKey(string FirstName, string LastName);

var userKey = new UserKey("Test first name", "Test last name");
cache.RetrieveAsync<User>(userKey);

In case no entity properties were configured as part of the caching key (it was configured with static string or class name), call the corresponding method without key

cache.RetrieveAsync<User>();

In the case of named policies, the policy name should be passed as well.

var userId = 42;
cache.RetrieveAsync<User>(userId, new PolicyName("UserPolicyName"));

3. Update

Just set a new value with the same key using CacheAsync.

4. Delete

To remove the value from the cache, the key should be passed. If the key is a scalar (one of the entity properties), it can be used directly.

var userId = 42;
cache.RemoveAsync<User>(userId);

In the case of a nonscalar value key (more than one of the entity properties), the key (class or struct) should contain corresponding properties with the same names as the configured entity properties.

record UserKey(string FirstName, string LastName);

var userKey = new UserKey("Test first name", "Test last name");
cache.RemoveAsync<User>(userKey);

In case no entity properties were configured as part of the caching key (it was configured with static string or class name), call the corresponding method without key

cache.RemoveAsync<User>();

In the case of named policies, the policy name should be passed as well.

var userId = 42;
cache.RemoveAsync<User>(userId, new PolicyName("UserPolicyName"));
Clone this wiki locally