在自定义Newtonsoft JsonConverter类中访问dbcontext [英] access dbcontext in custom Newtonsoft JsonConverter class

查看:171
本文介绍了在自定义Newtonsoft JsonConverter类中访问dbcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
    }
}

问题是我无法在ReadJson中获取数据库上下文()
使用Scoped生命周期将dbcontext添加到服务容器

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")));

这是我如何使用IdsJsonConverter

this is how I use IdsJsonConverter

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


推荐答案

您可以在ConfigureServices中调用以下代码



You can call below code in your ConfigureServices

var serviceProvider = services.BuildServiceProvider();

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

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

在您的ReadJson

In your ReadJson

App.ServiceProvider.GetService<MyDatabase>();

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

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

这篇关于在自定义Newtonsoft JsonConverter类中访问dbcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆