我正在寻找一些关于以下目标的最佳模式的指针。
我有多个服务,我想发送作业,但将包含元数据,将形成单独的对象DataObject。我在想下面的
public enum JobType
{
Job1 = 0,
Job2 = 1,
Job3 = 2
}
public class BaseJob
{
/// <summary>
/// Unique id maybe a guid
/// </summary>
public string Id { get; set; }
}
public interface IJob<T>
{
/// <summary>
/// Enumeration of a type of job
/// </summary>
JobType Job { get; set; }
/// <summary>
/// Serialized object JsonConvert.SerializeObject(data);
/// </summary>
string DataObject { get; set; }
/// <summary>
/// DeSerialized object of Type T;
/// </summary>
T Object { get; }
/// <summary>
/// Unique id maybe a guid
/// </summary>
string Id { get; set; }
/// <summary>
/// Create the job object natively
/// </summary>
/// <param name="data"></param>
void SetJobInfo(T data);
}
public class Job<T>: BaseJob, IJob<T>
{
/// <inheritdoc/>
public JobType Job { get; set; }
/// <inheritdoc/>
public string DataObject { get; set; }
[JsonIgnore]
public T Object => JsonConvert.DeserializeObject<T>(DataObject);
/// <inheritdoc/>
public void SetJobInfo(T data)
{
DataObject = JsonConvert.SerializeObject(data);
}
}
我可以使用工厂方法从一个微服务创建相关的作业,但是我如何从另一个服务检查类型是什么?如果可能的话,我尽量不要在多个地方有逻辑。
当我从作业DTO反序列化数据对象时,在作业类型中定义T的最佳方法是什么?
public void GetJob(IJob<dynamic> job)
{
switch (job.Job)
{
case JobType.Job1:
// How do I get the T of the object
var object1 = job.Object;
// I would like to use T to do something..
break;
case JobType.Job2:
break;
case JobType.Job3:
break;
default:
throw new ArgumentOutOfRangeException(nameof(job), job, null);
}
}
感谢当使用Newtonsoft序列化对象时,您可以启用TypeNameHandling
,这将添加一个$type
。
var serializedObject = JsonConvert.SerializeObject(myObject,
Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
});
在接收微服务中,您将使用:
var deserializedObject = JsonConvert.SerializeObject(myObject, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
});
它将存储在JSON中对象表示的顶部:
{
"$type": "...",
"Property_1": "...",
"Property_2": "..."
}
参见文档中的完整示例。