I'm fairly new to writing generic transform model extensions and I was trying to go from a model to an Azure service bus message which works as expected. But I'm now trying to do the reverse where it can go from a message to a specified type.
The extension method currently looks like so:
public static class ModelExtensions
{
public static Message ToMessage<TModel>(this TModel model) =>
new Message(
Encoding.UTF8.GetBytes(
JsonConvert.SerializeObject(model)));
public static TType FromMessage<TModel, TType>(this TModel model)
{
return JsonConvert.DeserializeObject<TType>(JsonConvert.SerializeObject(model));
}
}
Is there a way to do the reverse of what I have just done to many types depending what is specified on the other side of the extension method for example if on the outside I have done something like:
message.FromMessage<SpecificType>()
Should be as simple as
public static TModel FromMessage<TModel>(this Message message)
=> JsonConvert.DeserializeObject<TModel>(Encoding.UTF8.GetString(message.Body));
Usage
var result = message.FromMessage<MyLovelyHorse>()