2
// http://code.google.com/p/servicestack/wiki/TypeSerializer
3
// ServiceStack.Text: .NET C# POCO Type Text Serializer.
6
// Demis Bellot (demis.bellot@gmail.com)
8
// Copyright 2011 Liquidbit Ltd.
10
// Licensed under the same terms of ServiceStack: new BSD license.
14
using System.Collections.Generic;
16
using System.Reflection;
17
using System.Threading;
18
using ServiceStack.Text.Common;
20
namespace ServiceStack.Text.Jsv
22
internal static class JsvWriter
24
public static readonly JsWriter<JsvTypeSerializer> Instance = new JsWriter<JsvTypeSerializer>();
26
private static Dictionary<Type, WriteObjectDelegate> WriteFnCache = new Dictionary<Type, WriteObjectDelegate>();
28
public static WriteObjectDelegate GetWriteFn(Type type)
32
WriteObjectDelegate writeFn;
33
if (WriteFnCache.TryGetValue(type, out writeFn)) return writeFn;
35
var genericType = typeof(JsvWriter<>).MakeGenericType(type);
36
var mi = genericType.GetMethod("WriteFn", BindingFlags.Public | BindingFlags.Static);
37
var writeFactoryFn = (Func<WriteObjectDelegate>)Delegate.CreateDelegate(typeof(Func<WriteObjectDelegate>), mi);
38
writeFn = writeFactoryFn();
40
Dictionary<Type, WriteObjectDelegate> snapshot, newCache;
43
snapshot = WriteFnCache;
44
newCache = new Dictionary<Type, WriteObjectDelegate>(WriteFnCache);
45
newCache[type] = writeFn;
47
} while (!ReferenceEquals(
48
Interlocked.CompareExchange(ref WriteFnCache, newCache, snapshot), snapshot));
54
Tracer.Instance.WriteError(ex);
59
public static void WriteLateBoundObject(TextWriter writer, object value)
61
if (value == null) return;
62
var writeFn = GetWriteFn(value.GetType());
64
var prevState = JsState.IsWritingDynamic;
65
JsState.IsWritingDynamic = true;
66
writeFn(writer, value);
67
JsState.IsWritingDynamic = prevState;
70
public static WriteObjectDelegate GetValueTypeToStringMethod(Type type)
72
return Instance.GetValueTypeToStringMethod(type);
77
/// Implement the serializer using a more static approach
79
/// <typeparam name="T"></typeparam>
80
internal static class JsvWriter<T>
82
private static readonly WriteObjectDelegate CacheFn;
84
public static WriteObjectDelegate WriteFn()
86
return CacheFn ?? WriteObject;
91
CacheFn = typeof(T) == typeof(object)
92
? JsvWriter.WriteLateBoundObject
93
: JsvWriter.Instance.GetWriteFn<T>();
96
public static void WriteObject(TextWriter writer, object value)
98
CacheFn(writer, value);
b'\\ No newline at end of file'