Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the ReferenceLoopHandling in signalR

I working on a project where we have a two applications; The first is a console app that populates a database and the second is a self hosted signalR service which broadcasts any changes that occur to the content of the database.

The console app sends the model that has changed and the service publishes it to all the interested parties. But there is a problem when the model has circular dependencies. I tried to do something like this:

var config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling =          ReferenceLoopHandling.Ignore;

but it doesn't seem to make any change; It still throws an exception Self referencing loop detected for property

Is there any easy way to set the ReferenceLoopHandling globally and make it have effect on any model that the converter acts upon?

like image 527
ppoliani Avatar asked Jan 12 '23 22:01

ppoliani


1 Answers

With SignalR 2 you can use the DepandyResolver to replace the Json.Net serializer. To resolve reference loop issues in my app, I used the following:

  protected void Application_Start()
  {
     var serializerSettings = new JsonSerializerSettings();
     serializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
     serializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;

     var serializer = JsonSerializer.Create(serializerSettings);
     GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer); 
  }

If you're using a hubProxy on the client, similar settings would be required:

hubProxy.JsonSerializer.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
hubProxy.JsonSerializer.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
like image 181
mbursill Avatar answered Jan 23 '23 04:01

mbursill