在自定义Newtonsoft JsonConverter类中访问dbcontext

时间:2016-12-16 03:13:56

标签: c# entity-framework asp.net-core-mvc

我创建了一个JsonConverter,用于将子实体映射到json中的id列表 例如childrens:[1,2,3]

public class IdsJsonConverter : JsonConverter
{ 
    public override bool CanConvert(Type objectType)
    {
        return objectType==typeof(ICollection);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        //problem convert ids back to entities because i can not get db context here so I unable to get the tracked entities from context
        return existingValue;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        IEnumerable collection = (IEnumerable)value;
        List<long> ids = new List<long>();
        foreach (var item in collection)
        {
            dynamic itemCollection = (dynamic)item;
            ids.Add(itemCollection.ID);
        }
        //successful convert to list of ids 
        serializer.Serialize(writer, ids);
    }
}

问题是我无法在ReadJson()中获取db上下文 dbcontext使用Scoped生存期

添加到服务容器中
 public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped((_) => new MyDatabase(Configuration.GetConnectionString("DefaultConnection")));

这就是我使用IdsJsonConverter的方式

    [JsonConverter(typeof(IdsJsonConverter))] 
    public virtual ICollection<TAG> TAGs { get; set; }

1 个答案:

答案 0 :(得分:1)

您可以在ConfigureServices

中调用以下代码
var serviceProvider = services.BuildServiceProvider();

然后在某个地方将此serviceProvider指定为静态变量。例如:App.ServiceProvider

在你的ReadJson

App.ServiceProvider.GetService<MyDatabase>();

您需要Microsoft.Framework.DependencyInjection才能工作。