I'm failing to get the Dependency Injection working for the following Newtonsoft JsonConverter in .NET Core 3.1.
I want to use it at the attribute level only, not at a global level. So, it should be executed only when the designated attribute(s) from a certain class(es).
JsonConverter
:
public class HelloWorldCustomConverter : JsonConverter<string>
{
private readonly IMyService _myService;
public HelloWorldCustomConverter(IMyService myService)
{
_myService = myService;
}
public override bool CanRead => false;
public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
{
// append a value using the injected service
writer.WriteValue($"{value}-{myService.GetValue()}");
}
}
Usage:
public class MyClass
{
public string Title { get; set; }
[JsonConverter(typeof(HelloWorldCustomConverter))]
public string Details { get; set; }
}
It's .NET Core 3.1 and Newtonsoft.json version 13.0.1.
I appreciate any help, thanks.
Edit 1
I checked lots of answers from StackOverflow but none worked for me so far. Most of them are rather out-dated or has something missing to get it working. Few of them which I checked already and it didn't work for me:
- Cannot replace default JSON contract resolver in ASP.NET Core 3
- Custom JsonConverter with parameters in .NET Core
- https://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm
- .Net Core Api - Custom JSON Resolver based on Request Values
- http://www.dotnet-programming.com/post/2017/05/07/Aspnet-core-Deserializing-Json-with-Dependency-Injection.aspx
Edit 2
I tried the post suggested as a duplicate reference but it doesn't work in my case.
I tried spinning my head around and various other options but no luck.
One of the suggested work around from James (dated: 2108), didn't work.
Ref: https://github.com/JamesNK/Newtonsoft.Json/issues/1910
You can try something like
public class JsonOptions : IConfigureOptions<MvcJsonOptions>
{
IHttpContextAccessor _accessor;
public JsonOptions(IHttpContextAccessor accessor)
{
_accessor = accessor;
}
public virtual void Configure(MvcJsonOptions options)
{
options.SerializerSettings.Converters.Add(new MyCustomConverter(_accessor));
}
}
Register it in your startup
services.AddSingleton<IConfigureOptions<MvcJsonOptions>, JsonOptions>()
(can't remember if IHttpContextAccessor is registered by default so you may need to register that one as well)
Then in your Read/WriteJson methods use _accessor.HttpContext to access the context of the request