带DI的Newtonsoft转换器



我创建了自定义转换器,它可以工作!但现在我在其中添加了服务,无法在Startup.cs 中注册转换器

public class CustomGuidConverter : JsonConverter<Guid>
{
private readonly ILocalizerService localizer;
public CustomGuidConverter(ILocalizerService localizer)
{
this.localizer = localizer;
}
/// <inheritdoc/>
public override Guid ReadJson(JsonReader reader, Type objectType, [AllowNull] Guid existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var rawValue = reader?.Value?.ToString() ?? string.Empty;
if (Guid.TryParse(rawValue, out Guid value))
{
return value;
}

throw new JsonReaderException(localizer.Get(LocalStrings.ConvertingError, rawValue));
}
/// <inheritdoc/>
public override void WriteJson(JsonWriter writer, [AllowNull] Guid value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}

但当我在Startup.cs中注册它时,我应该创建对象切换依赖项。

.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new CustomGuidConverter(--inject service here--));
options.SerializerSettings.Converters.Add(new CustomDecimalConverter());
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
});

怎么能做到?

要使用DI配置选项,您需要注册选项配置器

创建你的类

public class NewtonsoftOptionsConfigurator : IPostConfigureOptions<MvcNewtonsoftJsonOptions>
{
public NewtonsoftOptionsConfigurator(
//You can inject services here
)
{
}
public void PostConfigure(string name, MvcNewtonsoftJsonOptions options)
{
//Configure options here
}
}

在将newtonsoft json选项添加到服务集合后,您需要注册配置程序

services.AddSingleton<IPostConfigureOptions<MvcNewtonsoftJsonOptions>, NewtonsoftOptionsConfigurator>();

最新更新