0

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; }
Charles Chou
  • 179
  • 1
  • 15
  • Can you save your IoC container as a static variable in some place. Then in your ReadJson, get that container and resolve your DbContext instance. – Kim Hoang Dec 16 '16 at 04:00
  • using static dbcontext seems not recommend in mvc core – Charles Chou Dec 16 '16 at 04:15
  • I mean the IoC Container, not the static dbcontext. I am not sure about MVC CORE, but using AutoFac, you should have a container, and you can store that container somewhere to use. – Kim Hoang Dec 16 '16 at 04:17
  • Your question maybe answer in this thread http://stackoverflow.com/questions/31863981/how-to-resolve-instance-inside-configureservices-in-asp-net-core – Kim Hoang Dec 16 '16 at 04:20
  • 1
    This seems like a bad architectural decision. Why would a JSON serializer have anything to do with fetching data from a data store? – Tieson T. Dec 16 '16 at 04:35
  • because this Converter was convert entities to an simple number list, it need to convert back to tracked entities by reading database. – Charles Chou Dec 16 '16 at 04:42

1 Answers1

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.

Charles Chou
  • 179
  • 1
  • 15
Kim Hoang
  • 1,338
  • 9
  • 24