Description
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:
- The
DefaultJsonSerializerFactory
tries to obtain aJsonSerializerOptions
from the DI container (no API change) - The
DefaultJsonSerializerFactory
is made public, taking aJsonSerializerOptions
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