-
-
Notifications
You must be signed in to change notification settings - Fork 673
/
ReactivePropertyResolver.cs
79 lines (67 loc) · 2.65 KB
/
ReactivePropertyResolver.cs
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
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reactive;
using System.Reflection;
using MessagePack.Formatters;
using Reactive.Bindings;
namespace MessagePack.ReactivePropertyExtension
{
public class ReactivePropertyResolver : IFormatterResolver
{
public static readonly ReactivePropertyResolver Instance = new ReactivePropertyResolver();
private ReactivePropertyResolver()
{
}
public IMessagePackFormatter<T>? GetFormatter<T>()
{
return FormatterCache<T>.Formatter;
}
private static class FormatterCache<T>
{
internal static readonly IMessagePackFormatter<T>? Formatter;
static FormatterCache()
{
Formatter = (IMessagePackFormatter<T>?)ReactivePropertyResolverGetFormatterHelper.GetFormatter(typeof(T));
}
}
}
internal static class ReactivePropertyResolverGetFormatterHelper
{
private static readonly Dictionary<Type, Type> FormatterMap = new Dictionary<Type, Type>()
{
{ typeof(ReactiveProperty<>), typeof(ReactivePropertyFormatter<>) },
{ typeof(IReactiveProperty<>), typeof(InterfaceReactivePropertyFormatter<>) },
{ typeof(IReadOnlyReactiveProperty<>), typeof(InterfaceReadOnlyReactivePropertyFormatter<>) },
{ typeof(ReactiveCollection<>), typeof(ReactiveCollectionFormatter<>) },
{ typeof(ReactivePropertySlim<>), typeof(ReactivePropertySlimFormatter<>) },
};
internal static object? GetFormatter(Type t)
{
if (t == typeof(Unit))
{
return UnitFormatter.Instance;
}
else if (t == typeof(Unit?))
{
return NullableUnitFormatter.Instance;
}
TypeInfo ti = t.GetTypeInfo();
if (ti.IsGenericType)
{
Type genericType = ti.GetGenericTypeDefinition();
Type formatterType;
if (FormatterMap.TryGetValue(genericType, out formatterType))
{
return CreateInstance(formatterType, ti.GenericTypeArguments);
}
}
return null;
}
private static object? CreateInstance(Type genericType, Type[] genericTypeArguments, params object[] arguments)
{
return Activator.CreateInstance(genericType.MakeGenericType(genericTypeArguments), arguments);
}
}
}