Using Interface Derived Classes with NEST

I'm having trouble using NEST's strongly-type objects with a nested list of Interface-Derived user roles.

I've posted a question about it on StackOverflow: http://stackoverflow.com/questions/36578801/using-interface-derived-classes-with-nest-and-elasticsearch

Specifically, NEST can't figure out the right class to use and throws an exception:

Could not create an instance of type IMediaDetectionRole. 
Type is an interface or abstract class and cannot be instantiated. 
Path 'hits.hits[0]._source.roles[0].name', line 1, position 343.

What is the "NESTy" way to solve this problem?

Many thanks!

-Z

I'm guessing your SO example is a simplified one? Otherwise you wouldn't need an interface at all.

You may be able to get around this using a custom JsonConverter over your Roles property. That would need to parse the json to some temp object, switch on the value of GetRoleType and hydrate and return the appropriate concrete object.

Or more simply, you could have just the one MediaDetectionRole class that you use with Elasticsearch, and expose a method like AsIMediaDetectionRole that does the switch for you after the fact.

Indeed this is a simplified example. Long term the various roles will have some differing features.

I documented my fix and updated the Stack Overflow question here: http://stackoverflow.com/questions/36578801/using-interface-derived-classes-with-nest-and-elasticsearch/36654644#36654644

Many thanks @KodrAus for your response and for steering me towards JSON.net for a solution and thanks to @Martijn_Laarman for showing me that I could resolve this issue using a [JsonProperty] attribute to force the rendering of Type information within the nested List.

Cheers!

-Z

1 Like