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
97 lines (82 loc) · 2.75 KB
/
Copy pathMessageFactory.cs
File metadata and controls
97 lines (82 loc) · 2.75 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
93
94
95
96
97
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 == 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);
#if NETFX_CORE
var mi = genericMessageType.GetRuntimeMethods().First(p => p.Name.Equals("Create"));
factoryFn = (MessageFactoryDelegate)mi.CreateDelegate(
typeof(MessageFactoryDelegate));
#else
var mi = genericMessageType.GetMethod("Create",
BindingFlags.Public | BindingFlags.Static);
factoryFn = (MessageFactoryDelegate)Delegate.CreateDelegate(
typeof(MessageFactoryDelegate), mi);
#endif
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 MessageError Error { 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 string.Format("CreatedDate={0}, Id={1}, Type={2}, Retry={3}",
this.CreatedDate,
this.Id.ToString("N"),
typeof(T).Name,
this.RetryAttempts);
}
}
}