Skip to content

[API Proposal]: HybridCache - make it easier to use custom JsonSerializerOptions #5827

Closed
@tyler-boyd

Description

@tyler-boyd

Background and motivation

The default HybridCache serializer uses JsonSerializer, but there is no way to configure the JsonSerializerOptions.

I think it is fairly common to have a custom JsonSerializerOptions which is helpful (or even necessary) for serializing cached types. Thus I think it would be helpful if it were easier to configure the JsonSerializerOptions used by the HybridCache.

As it stands now, you have to write your own serializer factory which is a lot of boilerplate.

API Proposal

In general I see 2 main options:

  1. The DefaultJsonSerializerFactory tries to obtain a JsonSerializerOptions from the DI container (no API change)
  2. The DefaultJsonSerializerFactory is made public, taking a JsonSerializerOptions parameter, so we can use it with .AddSerializerFactory(...) instead of re-implementing it

API Usage

For option 1, there's no change, you'd just need to add a singleton JsonSerializerOptions to DI

For option 2, it would look something like this:

var jsonSerializerOptions = BuildJsonSerializerOptions();
services.AddHybridCache(opts =>
{
    opts.DefaultEntryOptions = new HybridCacheEntryOptions { Expiration = TimeSpan.FromMinutes(5) };
}).AddSerializerFactory(new DefaultJsonSerializerFactory(jsonSerializerOptions));

Alternative Designs

No response

Risks

Option 1 could be considered a breaking change since the JSON serialization behaviour would change, however the hybrid cache is still experimental. Option 2 should not break anything.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions