Get configurated serializer in Mutex or Behavior?

I have an incoming Mutator. If needed, I can upgrade it to a Behavior.

In this Mutator I’m processing a raw (not NServiceBus) message to a message that NserviceBus understands.

I am serializing the message in the Mutator, but the serializer is now hard coded to Newtonsoft.Json.

Can I get the current serializer that has been configurated in NServiceBus from the Mutator and use this to serialize? If not, can I do this in a Behavior?

Hi Remy,

Unfortunately, we are currently neither registering the main serializer nor the serializer resolver in the DI container. NServiceBus itself does pass it to the relevant behaviors directly internally. It does sound like this might be a valid feature request. Would you mind opening an issue in the NServiceBus repository describing a bit more your scenario?

There is a slightly cumbersome way that would allow you to get the main serializer. You would have to mimic part of what the serializer feature does. You could inject IReadOnlySettings in your behavior and then initialize your “own” main serializer by pulling out the serializer definition. The pseudocode would look something like

var mapper = mainSettings.Get<IMessageMapper>();
var definitionAndSettings = mainSettings.Get<Tuple<SerializationDefinition, SettingsHolder>>("MainSerializer");
var definition = definitionAndSettings.Item1;
var deserializerSettings = definitionAndSettings.Item2;
// the following two methods are internal and would have to be called via reflection but I think you might be able to omit those
deserializerSettings.Merge(mainSettings);
deserializerSettings.PreventChanges();
var serializerFactory = definition.Configure(deserializerSettings);
var serializer = serializerFactory(mapper);

see https://github.com/Particular/NServiceBus/blob/master/src/NServiceBus.Core/Serialization/SerializationFeature.cs#L24-L31

Sorry, I would have loved to give you a more straightforward answer.

Regards,
Daniel

1 Like

Hi Daniel,

Thank you very much for the detailed info. I will create an issue for it.

I will try if I get it working with your suggestion!

Regards,
Remy