forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageFactory.cs
More file actions
92 lines (76 loc) · 2.61 KB
/
MessageFactory.cs
File metadata and controls
92 lines (76 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
namespace ServiceStack.Messaging
{
internal delegate IMessage MessageFactoryDelegate(object body);
public static class MessageFactory
{
static readonly Dictionary<Type, MessageFactoryDelegate> CacheFn
= new Dictionary<Type, MessageFactoryDelegate>();
public static IMessage Create(object response)
{
if (response is IMessage responseMessage)
return responseMessage;
if (response == null) return null;
var type = response.GetType();
MessageFactoryDelegate factoryFn;
lock (CacheFn) CacheFn.TryGetValue(type, out factoryFn);
if (factoryFn != null)
return factoryFn(response);
var genericMessageType = typeof(Message<>).MakeGenericType(type);
var mi = genericMessageType.GetMethod("Create",
BindingFlags.Public | BindingFlags.Static);
factoryFn = (MessageFactoryDelegate)Delegate.CreateDelegate(
typeof(MessageFactoryDelegate), mi);
lock (CacheFn) CacheFn[type] = factoryFn;
return factoryFn(response);
}
}
public class Message : IMessage
{
public Guid Id { get; set; }
public DateTime CreatedDate { get; set; }
public long Priority { get; set; }
public int RetryAttempts { get; set; }
public Guid? ReplyId { get; set; }
public string ReplyTo { get; set; }
public int Options { get; set; }
public ResponseStatus Error { get; set; }
public string Tag { get; set; }
public Dictionary<string, string> Meta { get; set; }
public object Body { get; set; }
}
/// <summary>
/// Basic implementation of IMessage[T]
/// </summary>
/// <typeparam name="T"></typeparam>
public class Message<T>
: Message, IMessage<T>
{
public Message()
{
this.Id = Guid.NewGuid();
this.CreatedDate = DateTime.UtcNow;
this.Options = (int)MessageOption.NotifyOneWay;
}
public Message(T body)
: this()
{
Body = body;
}
public static IMessage Create(object oBody)
{
return new Message<T>((T)oBody);
}
public T GetBody()
{
return (T)Body;
}
public override string ToString()
{
return $"CreatedDate={this.CreatedDate}, Id={this.Id:N}, Type={typeof(T).Name}, Retry={this.RetryAttempts}";
}
}
}