问题
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