Click or drag to resize

IAdhocCacheService Interface

Defines a service which can store commonly used objects in a transient cache

Namespace:  SanteDB.Core.Services
Assembly:  SanteDB.Core.Api (in SanteDB.Core.Api.dll) Version: 2.2.1
Syntax
public interface IAdhocCacheService : IServiceImplementation

The IAdhocCacheService type exposes the following members.

Properties
  NameDescription
Public propertyServiceName
Gets the service name
(Inherited from IServiceImplementation.)
Top
Methods
Remarks

The ad-hoc cache service differs from the data cache in that the ad-hoc cache can be used to store any data with any key and value within the caching technology implementation. The cache is commonly used to store repeat or commonly fetched data (for example policy decision outcomes, keys, reference term lookups, etc.).

The cache can be used to save fetching and querying data to/from the persistence layer.

Note to Implementers: Your implementation of this interface should not be a persistent cache (if possible to enforce). The callers of this interface typically assume a short lifecycle of data within the cache, and transient, rapid access should be prioritized over durability.

Examples
Implementing a Cache Service
// A horrible implementation of the cache service that uses a simple dictionary
public class DictionaryCache : IAdHocCacheService {

    private ConcurrentDictionary<String, Object> m_cache = new ConcurrentDictionary<String, Object>();

    // Add an object to cache
    public void Add<T>(String key, T value, TimeSpan? timeout = null) {
        this.m_cache.TryAdd(key, value); // note: we won't implement timeouts
    }

    public T Get<T>(String key) {
        if(this.m_cache.TryGetValue(key, out T retVal))
        {
            return retVal;
        }
        else
        {
            return default(T);
        }
    }

    public bool Remove(String key) {
        this.m_cache.TryRemove(key, out _);
    }
}
Examples
Using the Ad-Hoc Cache
bool IsAUser(String userName) {
    var cacheService = ApplicationServiceContext.Current.GetService<IAdhocCacheService>();
    // Attempt to load what we're looking for in the cache
    var cachedResult = cacheService?.Get<bool?>($"isAUser.{userName}");
    if(!cachedResult.HasValue) {
        var persistenceService = ApplicationServiceContext.Current.GetService<IRepositoryService<SecurityUser>>();
        cachedResult = persistenceService.Count(o=>o.UserName == userName, AuthenticationContext.SystemPrincipal) > 0;
        cacheService?.Add($"isAUser.{userName}", cacheResult);
    }
    return cacheResult;
See Also