Message deserialization exception thrown when event has Interfaces as properties

I am getting a message deserialization exception when NServicebus is trying to deserialize message which has properties that are Interfaces.
example:

public interface IAccount
{
string CustomerID {get;}
IAddress Address {get;}
}

exception:
Newtonsoft.Json.JsonSerializationException: Could not create an instance of type IAddress type is an interface or abstract class and cannot be instantiated.
Is my assumption that proxy classes for these interfaces should be created? Am I missing some configuration ?

It is recommended to use POCO’s for messages. Deserialization of interfaces requires type information to be serialized within the payload which usually is considered a bad practice. Especially when exchanging messages between autonomous components where often its better to only exchange flat human readable XML/JSON.

If you really want you can use a different TypeNameHandling value:

1 Like

@ppula We just ran into something similar a few weeks ago and this suggestion from Mike Minutillo was helpful to us to get the service up and running until we had time modify the upstream services message contracts into POCO’s.

AssemblyScanner cannot find concrete serialization types from unobtrusive assembly · Issue #6967 · Particular/NServiceBus (github.com)

Here is a slightly refactored version of that same code:
Case 86015: Repro With Interface member by bbrandt · Pull Request #7 · mikeminutillo/SupportRepro (github.com)

In our example we do not have concrete implementation of the interfaces, for a workaround for the time being we have created concrete implementations and have just like on the example above changed the message type header to point at the concrete class so we are able to deserialize. We are making a transition from MassTransit so messages we are consuming already had the need for a MassTransit behavior class.
Would like to point out though that MassTransit has no problem deserializing these as they have InterfaceProxyConverter for this purpose.

@ppula I didn’t test the following with the NewtonsoftJson serializer but if you have concrete types available you could try this approach:

We do not support deserializing interface to anonymous proxies out of the box. Likely that could be accomplished by customizing the newtonsoft serializer configuration.

Unfortunately, I do not control the serialization of the message. I had tried playing with TypeNameHandling however that did not work.