Hello Sergey!
We are trying out Hangfire for our product at my company as it solves many of our needs. We are building a site that have the requirement to be able to send asynchronous commands. We think Hangfire looks awesome!
We have a method Send(ICommand command)
that we want to call via Hangfire. Everyting works great exept that when MyAsyncCommand
(that is an ICommand
) is serialized it does not contain any type information. So when Send
is entered by Hangfire the command is null.
I cloned the Hangfire repo and made a small edit in the JobHelper file that solves the problem:
JsonConvert.SerializeObject
can take in a JsonSerializerSettings
object and if I set the property TypeNameHandling
to TypeNameHandling.Objects
, the type information is added to the serialized string. We need to add the same settings to the DeserializeObject
method.
public static string ToJson(object value)
{
return value != null
? JsonConvert.SerializeObject(value, Formatting.None, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
})
: null;
}
public static T FromJson<T>(string value)
{
return value != null
? JsonConvert.DeserializeObject<T>(value, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
})
: default(T);
}
public static object FromJson(string value, [NotNull] Type type)
{
if (type == null) throw new ArgumentNullException("type");
return value != null
? JsonConvert.DeserializeObject(value, type, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects
})
: null;
}
So the Arguments column in the table Hangfire.Job goes from
["{\"Id\":\"f514f8a5-aa97-413d-86d6-ad04b3a7acae\"}"]
to
["\"$type\":\"MySolution.MyAsyncCommand, MySolution\",\"Id\":\"35c071e5-17ab-48c3-bbc1-344e9d943f7c\"}"]
What do you think about this? Is there any other way to solve the problem? If you need any more examples just ask!
Best regards,
Jonatan