access dbcontext in custom Newtonsoft JsonConverter class

限于喜欢 提交于 2019-12-12 03:56:43

问题


I created an JsonConverter for mapping children entitys to list of ids in json for example 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);
    }
}

the problem is i can not get db context in ReadJson() the dbcontext is added to the services container using the Scoped lifetime

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped((_) => new MyDatabase(Configuration.GetConnectionString("DefaultConnection")));

this is how I use IdsJsonConverter

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

回答1:


You can call below code in your ConfigureServices

var serviceProvider = services.BuildServiceProvider();

Then assign this serviceProvider as a static variable in some place. Eg: App.ServiceProvider.

In your ReadJson

App.ServiceProvider.GetService<MyDatabase>();

You need Microsoft.Framework.DependencyInjection for this to work.



来源:https://stackoverflow.com/questions/41176724/access-dbcontext-in-custom-newtonsoft-jsonconverter-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!