Skip to content

Caching

Requests

To reduce the number of requests to the Dataverse instance, the IDataverseService supports caching. This is handled with HybridCache -- which supports an in-memory L1 cache, and any L2 cache that implements IDistributedCache.

To use caching, set your request object to implement IDataverseCachedRequest instead of IDataverseRequest. This interface includes two properties which define how the response is cached.

  • CacheKey
  • Defines the key of the item in cache.
  • CacheDuration
  • Defines how long the cached value should remain valid in the

Avoiding cache collisions

To prevent cache collisions in scenarios where you are connected to multiple Dataverse instances, the DataverseServiceCache will automatically include the Organization ID in the underlying cache key name.

Example

In the following example, the User ID response will be cached for 5 minutes.

public class GetUserIdRequest : IDataverseCachedRequest<Guid>
{
    public string CacheKey => "WhoAmI";

    public TimeSpan CacheDuration => TimeSpan.FromMinutes(5);

    public async Task<Guid> Execute(IDataverseService service, ILogger logger, CancellationToken cancellationToken = default)
    {
        var response = (WhoAmIResponse)await service.ExecuteAsync(new WhoAmIRequest());

        return response.UserId;
    }
}

Distributed Cache

You can use any distributed cache by registering an IDistributedCache service into the Dependency Injection container. There are a few pre-existing packages which can do this:

Cache Package
SQL Microsoft.Extensions.Caching.SqlServer
Redis Microsoft.Extensions.Caching.StackExchangeRedis
NCache NCache.Microsoft.Extensions.Caching.OpenSource

You can read more about Distributed Caching here.

Cache Service

The underlying HybridCache service is exposed via the DataverseServiceCache. This exists as the Cache property on the IDataverseService. Normally, you should not need to interact with this, however, it can be usefull if you need to manually invalidate/remove a cache key. Just keep in mind that if your service is running on multiple instances, removing a cache entry only removes it from the memory of the current instance.

Invalidation

To invalidate/remove a cache entry, simply use the Remove method.

await service.Cache.Remove("WhoAmI", cancellationToken);