1

I would like to use a JsonConverter<> which has dependency, and that dependency can not be a singleton, instead should be resolve as scoped...

I have to configure my System.Text.JsonConverter in Startup, so I must provide the JsonSerializaionOptions along with my JsonConverter<> instance in Startup. I can live together the JsonConverter<> as singleton, I instantiate myself, but how can I inject its scoped dependencies?

The only horrible thing comes in my mind to have a IServiceProvider property, and some other logic later (middleware?) checks if that property is initialized and initializes it. So in the actual Read and Write methods of the JsonConverter<> can access to the scoped dependency via the IServiceProvider.

This sounds sooo errorprone and smells, once because of timing (what is the actual conversion occurs before the property injection), but my main concern is the concurrency, having this JsonConverter<> a singleton by design, so the very same IServiceProvider instance in the injected property will be used concurrently by all the web app threads...

What am I missing here?

  • Is having a scoped dependency for a JsonConverter<> smells?
  • Is there a way to not instantiate the JsonConverter<> in Startup? (yes I know I could instantiate JsonSerializerOptions and do manually the serialization with JsonConverter), but this way I can not use many built in json support of ASP.NET Core
g.pickardou
  • 32,346
  • 36
  • 123
  • 268
  • What kind of logic do you wish to inject into that JsonConverter? – Steven May 25 '20 at 08:13
  • Did you read [this](https://stackoverflow.com/a/21861473/264697)? – Steven May 25 '20 at 08:15
  • Many thanks reading my question. In general: it is a request specific thing. The concrete case is the depends on browser timezone, which I could detect from my cookie. Why I would do this? Long story but the full issue with the JsonSerializer is described here in detail, it is closed, obviously was too much, imho it is clear :-) https://stackoverflow.com/q/61984200/1157814 – g.pickardou May 25 '20 at 08:35

0 Answers0