/
SerializerBuilder.cs
executable file
·758 lines (673 loc) · 36.7 KB
/
SerializerBuilder.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
// This file is part of YamlDotNet - A .NET library for YAML.
// Copyright (c) Antoine Aubry and contributors
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do
// so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using System;
using System.Collections.Generic;
#if NET7_0_OR_GREATER
using System.Diagnostics.CodeAnalysis;
#endif
using YamlDotNet.Core;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
namespace YamlDotNet.Serialization
{
/// <summary>
/// Creates and configures instances of <see cref="Serializer" />.
/// This class is used to customize the behavior of <see cref="Serializer" />. Use the relevant methods
/// to apply customizations, then call <see cref="Build" /> to create an instance of the serializer
/// with the desired customizations.
/// </summary>
#if NET7_0_OR_GREATER
[RequiresDynamicCode("This builder configures the serializer to use reflection which is not compatible with ahead-of-time compilation or assembly trimming." +
" You need to use the code generator/analyzer to generate static code and use the 'StaticSerializerBuilder' object instead of this one.")]
#endif
public sealed class SerializerBuilder : BuilderSkeleton<SerializerBuilder>
{
private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory;
private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;
private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;
private readonly LazyComponentRegistrationList<IEventEmitter, IEventEmitter> eventEmitterFactories;
private readonly IDictionary<Type, TagName> tagMappings = new Dictionary<Type, TagName>();
private readonly IObjectFactory objectFactory;
private int maximumRecursion = 50;
private EmitterSettings emitterSettings = EmitterSettings.Default;
private DefaultValuesHandling defaultValuesHandlingConfiguration = DefaultValuesHandling.Preserve;
private ScalarStyle defaultScalarStyle = ScalarStyle.Any;
private bool quoteNecessaryStrings;
private bool quoteYaml1_1Strings;
public SerializerBuilder()
: base(new DynamicTypeResolver())
{
typeInspectorFactories.Add(typeof(CachedTypeInspector), inner => new CachedTypeInspector(inner));
typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), inner => namingConvention is NullNamingConvention ? inner : new NamingConventionTypeInspector(inner, namingConvention));
typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), inner => new YamlAttributesTypeInspector(inner));
typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), inner => overrides != null ? new YamlAttributeOverridesInspector(inner, overrides.Clone()) : inner);
preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>>
{
{ typeof(AnchorAssigner), typeConverters => new AnchorAssigner(typeConverters) }
};
emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>>
{
{
typeof(CustomSerializationObjectGraphVisitor),
args => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer)
},
{
typeof(AnchorAssigningObjectGraphVisitor),
args => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor<AnchorAssigner>())
},
{
typeof(DefaultValuesObjectGraphVisitor),
args => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory())
},
{
typeof(CommentsObjectGraphVisitor),
args => new CommentsObjectGraphVisitor(args.InnerVisitor)
}
};
eventEmitterFactories = new LazyComponentRegistrationList<IEventEmitter, IEventEmitter>
{
{
typeof(TypeAssigningEventEmitter), inner =>
new TypeAssigningEventEmitter(inner,
tagMappings,
quoteNecessaryStrings,
quoteYaml1_1Strings,
defaultScalarStyle,
yamlFormatter,
enumNamingConvention)
}
};
objectFactory = new DefaultObjectFactory();
objectGraphTraversalStrategyFactory = (typeInspector, typeResolver, typeConverters, maximumRecursion) =>
new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, objectFactory);
}
protected override SerializerBuilder Self { get { return this; } }
/// <summary>
/// Put double quotes around strings that need it, for example Null, True, False, a number. This should be called before any other "With" methods if you want this feature enabled.
/// </summary>
/// <param name="quoteYaml1_1Strings">Also quote strings that are valid scalars in the YAML 1.1 specification (which includes boolean Yes/No/On/Off, base 60 numbers and more)</param>
public SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false)
{
quoteNecessaryStrings = true;
this.quoteYaml1_1Strings = quoteYaml1_1Strings;
return this;
}
/// <summary>
/// Sets the default quoting style for scalar values. The default value is <see cref="ScalarStyle.Any"/>
/// </summary>
public SerializerBuilder WithDefaultScalarStyle(ScalarStyle style)
{
this.defaultScalarStyle = style;
return this;
}
/// <summary>
/// Sets the maximum recursion that is allowed while traversing the object graph. The default value is 50.
/// </summary>
public SerializerBuilder WithMaximumRecursion(int maximumRecursion)
{
if (maximumRecursion <= 0)
{
throw new ArgumentOutOfRangeException(nameof(maximumRecursion), $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer.");
}
this.maximumRecursion = maximumRecursion;
return this;
}
/// <summary>
/// Registers an additional <see cref="IEventEmitter" /> to be used by the serializer.
/// </summary>
/// <param name="eventEmitterFactory">A function that instantiates the event emitter.</param>
public SerializerBuilder WithEventEmitter<TEventEmitter>(Func<IEventEmitter, TEventEmitter> eventEmitterFactory)
where TEventEmitter : IEventEmitter
{
return WithEventEmitter(eventEmitterFactory, w => w.OnTop());
}
/// <summary>
/// Registers an additional <see cref="IEventEmitter" /> to be used by the serializer.
/// </summary>
/// <param name="eventEmitterFactory">A function that instantiates the event emitter.</param>
/// <param name="where">Configures the location where to insert the <see cref="IEventEmitter" /></param>
public SerializerBuilder WithEventEmitter<TEventEmitter>(
Func<IEventEmitter, TEventEmitter> eventEmitterFactory,
Action<IRegistrationLocationSelectionSyntax<IEventEmitter>> where
)
where TEventEmitter : IEventEmitter
{
if (eventEmitterFactory == null)
{
throw new ArgumentNullException(nameof(eventEmitterFactory));
}
if (where == null)
{
throw new ArgumentNullException(nameof(where));
}
where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), inner => eventEmitterFactory(inner)));
return Self;
}
/// <summary>
/// Registers an additional <see cref="IEventEmitter" /> to be used by the serializer.
/// </summary>
/// <param name="eventEmitterFactory">A function that instantiates the event emitter based on a previously registered <see cref="IEventEmitter" />.</param>
/// <param name="where">Configures the location where to insert the <see cref="IEventEmitter" /></param>
public SerializerBuilder WithEventEmitter<TEventEmitter>(
WrapperFactory<IEventEmitter, IEventEmitter, TEventEmitter> eventEmitterFactory,
Action<ITrackingRegistrationLocationSelectionSyntax<IEventEmitter>> where
)
where TEventEmitter : IEventEmitter
{
if (eventEmitterFactory == null)
{
throw new ArgumentNullException(nameof(eventEmitterFactory));
}
if (where == null)
{
throw new ArgumentNullException(nameof(where));
}
where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (wrapped, inner) => eventEmitterFactory(wrapped, inner)));
return Self;
}
/// <summary>
/// Unregisters an existing <see cref="IEventEmitter" /> of type <typeparam name="TEventEmitter" />.
/// </summary>
public SerializerBuilder WithoutEventEmitter<TEventEmitter>()
where TEventEmitter : IEventEmitter
{
return WithoutEventEmitter(typeof(TEventEmitter));
}
/// <summary>
/// Unregisters an existing <see cref="IEventEmitter" /> of type <param name="eventEmitterType" />.
/// </summary>
public SerializerBuilder WithoutEventEmitter(Type eventEmitterType)
{
if (eventEmitterType == null)
{
throw new ArgumentNullException(nameof(eventEmitterType));
}
eventEmitterFactories.Remove(eventEmitterType);
return this;
}
/// <summary>
/// Registers a tag mapping.
/// </summary>
public override SerializerBuilder WithTagMapping(TagName tag, Type type)
{
if (tag.IsEmpty)
{
throw new ArgumentException("Non-specific tags cannot be maped");
}
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (tagMappings.TryGetValue(type, out var alreadyRegisteredTag))
{
throw new ArgumentException($"Type already has a registered tag '{alreadyRegisteredTag}' for type '{type.FullName}'", nameof(type));
}
tagMappings.Add(type, tag);
return this;
}
/// <summary>
/// Unregisters an existing tag mapping.
/// </summary>
public SerializerBuilder WithoutTagMapping(Type type)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (!tagMappings.Remove(type))
{
throw new KeyNotFoundException($"Tag for type '{type.FullName}' is not registered");
}
return this;
}
/// <summary>
/// Ensures that it will be possible to deserialize the serialized objects.
/// This option will force the emission of tags and emit only properties with setters.
/// </summary>
public SerializerBuilder EnsureRoundtrip()
{
objectGraphTraversalStrategyFactory = (typeInspector, typeResolver, typeConverters, maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(
typeConverters,
typeInspector,
typeResolver,
maximumRecursion,
namingConvention,
settings,
objectFactory
);
WithEventEmitter(inner =>
new TypeAssigningEventEmitter(inner,
tagMappings,
quoteNecessaryStrings,
quoteYaml1_1Strings,
defaultScalarStyle,
yamlFormatter,
enumNamingConvention), loc => loc.InsteadOf<TypeAssigningEventEmitter>());
return WithTypeInspector(inner => new ReadableAndWritablePropertiesTypeInspector(inner), loc => loc.OnBottom());
}
/// <summary>
/// Specifies that, if the same object appears more than once in the
/// serialization graph, it will be serialized each time instead of just once.
/// </summary>
/// <remarks>
/// If the serialization graph contains circular references and this flag is set,
/// a StackOverflowException will be thrown.
/// If this flag is not set, there is a performance penalty because the entire
/// object graph must be walked twice.
/// </remarks>
public SerializerBuilder DisableAliases()
{
preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner));
emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor));
return this;
}
/// <summary>
/// Forces every value to be serialized, even if it is the default value for that type.
/// </summary>
[Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", error: true)]
public SerializerBuilder EmitDefaults() => ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve);
/// <summary>
/// Configures how properties with default and null values should be handled. The default value is DefaultValuesHandling.Preserve
/// </summary>
/// <remarks>
/// If more control is needed, create a class that extends from ChainedObjectGraphVisitor and override its EnterMapping methods.
/// Then register it as follows:
/// WithEmissionPhaseObjectGraphVisitor(args => new MyDefaultHandlingStrategy(args.InnerVisitor));
/// </remarks>
public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration)
{
this.defaultValuesHandlingConfiguration = configuration;
return this;
}
/// <summary>
/// Ensures that the result of the serialization is valid JSON.
/// </summary>
public SerializerBuilder JsonCompatible()
{
this.emitterSettings = this.emitterSettings
.WithMaxSimpleKeyLength(int.MaxValue)
.WithoutAnchorName();
return this
.WithTypeConverter(new GuidConverter(true), w => w.InsteadOf<GuidConverter>())
.WithTypeConverter(new DateTimeConverter(doubleQuotes: true))
#if NET6_0_OR_GREATER
.WithTypeConverter(new DateOnlyConverter(doubleQuotes: true))
.WithTypeConverter(new TimeOnlyConverter(doubleQuotes: true))
#endif
.WithEventEmitter(inner => new JsonEventEmitter(inner, yamlFormatter, enumNamingConvention), loc => loc.InsteadOf<TypeAssigningEventEmitter>());
}
/// <summary>
/// Allows you to override the new line character to use when serializing to YAML.
/// </summary>
/// <param name="newLine">NewLine character(s) to use when serializing to YAML.</param>
public SerializerBuilder WithNewLine(string newLine)
{
this.emitterSettings = this.emitterSettings.WithNewLine(newLine);
return this;
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{Nothing}" /> to be used by the serializer
/// before emitting an object graph.
/// </summary>
/// <remarks>
/// Registering a visitor in the pre-processing phase enables to traverse the object graph once
/// before actually emitting it. This allows a visitor to collect information about the graph that
/// can be used later by another visitor registered in the emission phase.
/// </remarks>
/// <param name="objectGraphVisitor">The type inspector.</param>
public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(TObjectGraphVisitor objectGraphVisitor)
where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
{
return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, w => w.OnTop());
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{Nothing}" /> to be used by the serializer
/// before emitting an object graph.
/// </summary>
/// <remarks>
/// Registering a visitor in the pre-processing phase enables to traverse the object graph once
/// before actually emitting it. This allows a visitor to collect information about the graph that
/// can be used later by another visitor registered in the emission phase.
/// </remarks>
/// <param name="objectGraphVisitorFactory">A function that instantiates the type inspector.</param>
public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<IEnumerable<IYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory)
where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
{
return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitorFactory, w => w.OnTop());
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{Nothing}" /> to be used by the serializer
/// before emitting an object graph.
/// </summary>
/// <remarks>
/// Registering a visitor in the pre-processing phase enables to traverse the object graph once
/// before actually emitting it. This allows a visitor to collect information about the graph that
/// can be used later by another visitor registered in the emission phase.
/// </remarks>
/// <param name="objectGraphVisitor">The type inspector.</param>
/// <param name="where">Configures the location where to insert the <see cref="IObjectGraphVisitor{Nothing}" /></param>
public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(
TObjectGraphVisitor objectGraphVisitor,
Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where
)
where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
{
if (objectGraphVisitor == null)
{
throw new ArgumentNullException(nameof(objectGraphVisitor));
}
if (where == null)
{
throw new ArgumentNullException(nameof(where));
}
where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), _ => objectGraphVisitor));
return this;
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{Nothing}" /> to be used by the serializer
/// before emitting an object graph.
/// </summary>
/// <remarks>
/// Registering a visitor in the pre-processing phase enables to traverse the object graph once
/// before actually emitting it. This allows a visitor to collect information about the graph that
/// can be used later by another visitor registered in the emission phase.
/// </remarks>
/// <param name="objectGraphVisitorFactory">A function that instantiates the type inspector.</param>
/// <param name="where">Configures the location where to insert the <see cref="IObjectGraphVisitor{Nothing}" /></param>
public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(
Func<IEnumerable<IYamlTypeConverter>, TObjectGraphVisitor> objectGraphVisitorFactory,
Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where
)
where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
{
if (objectGraphVisitorFactory == null)
{
throw new ArgumentNullException(nameof(objectGraphVisitorFactory));
}
if (where == null)
{
throw new ArgumentNullException(nameof(where));
}
where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), typeConverters => objectGraphVisitorFactory(typeConverters)));
return this;
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{Nothing}" /> to be used by the serializer
/// before emitting an object graph.
/// </summary>
/// <remarks>
/// Registering a visitor in the pre-processing phase enables to traverse the object graph once
/// before actually emitting it. This allows a visitor to collect information about the graph that
/// can be used later by another visitor registered in the emission phase.
/// </remarks>
/// <param name="objectGraphVisitorFactory">A function that instantiates the type inspector based on a previously registered <see cref="IObjectGraphVisitor{Nothing}" />.</param>
/// <param name="where">Configures the location where to insert the <see cref="IObjectGraphVisitor{Nothing}" /></param>
public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(
WrapperFactory<IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory,
Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where
)
where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
{
if (objectGraphVisitorFactory == null)
{
throw new ArgumentNullException(nameof(objectGraphVisitorFactory));
}
if (where == null)
{
throw new ArgumentNullException(nameof(where));
}
where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (wrapped, _) => objectGraphVisitorFactory(wrapped)));
return this;
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{Nothing}" /> to be used by the serializer
/// before emitting an object graph.
/// </summary>
/// <remarks>
/// Registering a visitor in the pre-processing phase enables to traverse the object graph once
/// before actually emitting it. This allows a visitor to collect information about the graph that
/// can be used later by another visitor registered in the emission phase.
/// </remarks>
/// <param name="objectGraphVisitorFactory">A function that instantiates the type inspector based on a previously registered <see cref="IObjectGraphVisitor{Nothing}" />.</param>
/// <param name="where">Configures the location where to insert the <see cref="IObjectGraphVisitor{Nothing}" /></param>
public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>(
WrapperFactory<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>, TObjectGraphVisitor> objectGraphVisitorFactory,
Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<Nothing>>> where
)
where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
{
if (objectGraphVisitorFactory == null)
{
throw new ArgumentNullException(nameof(objectGraphVisitorFactory));
}
if (where == null)
{
throw new ArgumentNullException(nameof(where));
}
where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (wrapped, typeConverters) => objectGraphVisitorFactory(wrapped, typeConverters)));
return this;
}
/// <summary>
/// Unregisters an existing <see cref="IObjectGraphVisitor{Nothing}" /> of type <typeparam name="TObjectGraphVisitor" />.
/// </summary>
public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor<TObjectGraphVisitor>()
where TObjectGraphVisitor : IObjectGraphVisitor<Nothing>
{
return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor));
}
/// <summary>
/// Unregisters an existing <see cref="IObjectGraphVisitor{Nothing}" /> of type <param name="objectGraphVisitorType" />.
/// </summary>
public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType)
{
if (objectGraphVisitorType == null)
{
throw new ArgumentNullException(nameof(objectGraphVisitorType));
}
preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType);
return this;
}
/// <summary>
/// Registers an <see cref="ObjectGraphTraversalStrategyFactory"/> to be used by the serializer
/// while traversing the object graph.
/// </summary>
/// <param name="objectGraphTraversalStrategyFactory">A function that instantiates the traversal strategy.</param>
public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory)
{
this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory;
return this;
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{IEmitter}" /> to be used by the serializer
/// while emitting an object graph.
/// </summary>
/// <param name="objectGraphVisitorFactory">A function that instantiates the type inspector.</param>
public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory)
where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
{
return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, w => w.OnTop());
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{IEmitter}" /> to be used by the serializer
/// while emitting an object graph.
/// </summary>
/// <param name="objectGraphVisitorFactory">A function that instantiates the type inspector.</param>
/// <param name="where">Configures the location where to insert the <see cref="IObjectGraphVisitor{IEmitter}" /></param>
public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(
Func<EmissionPhaseObjectGraphVisitorArgs, TObjectGraphVisitor> objectGraphVisitorFactory,
Action<IRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where
)
where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
{
if (objectGraphVisitorFactory == null)
{
throw new ArgumentNullException(nameof(objectGraphVisitorFactory));
}
if (where == null)
{
throw new ArgumentNullException(nameof(where));
}
where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), args => objectGraphVisitorFactory(args)));
return this;
}
/// <summary>
/// Registers an additional <see cref="IObjectGraphVisitor{IEmitter}" /> to be used by the serializer
/// while emitting an object graph.
/// </summary>
/// <param name="objectGraphVisitorFactory">A function that instantiates the type inspector based on a previously registered <see cref="IObjectGraphVisitor{IEmitter}" />.</param>
/// <param name="where">Configures the location where to insert the <see cref="IObjectGraphVisitor{IEmitter}" /></param>
public SerializerBuilder WithEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>(
WrapperFactory<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>, TObjectGraphVisitor> objectGraphVisitorFactory,
Action<ITrackingRegistrationLocationSelectionSyntax<IObjectGraphVisitor<IEmitter>>> where
)
where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
{
if (objectGraphVisitorFactory == null)
{
throw new ArgumentNullException(nameof(objectGraphVisitorFactory));
}
if (where == null)
{
throw new ArgumentNullException(nameof(where));
}
where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (wrapped, args) => objectGraphVisitorFactory(wrapped, args)));
return this;
}
/// <summary>
/// Unregisters an existing <see cref="IObjectGraphVisitor{IEmitter}" /> of type <typeparam name="TObjectGraphVisitor" />.
/// </summary>
public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor<TObjectGraphVisitor>()
where TObjectGraphVisitor : IObjectGraphVisitor<IEmitter>
{
return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor));
}
/// <summary>
/// Unregisters an existing <see cref="IObjectGraphVisitor{IEmitter}" /> of type <param name="objectGraphVisitorType" />.
/// </summary>
public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType)
{
if (objectGraphVisitorType == null)
{
throw new ArgumentNullException(nameof(objectGraphVisitorType));
}
emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType);
return this;
}
/// <summary>
/// Creates sequences with extra indentation
/// </summary>
/// <example>
/// list:
/// - item
/// - item
/// </example>
/// <returns></returns>
public SerializerBuilder WithIndentedSequences()
{
emitterSettings = emitterSettings.WithIndentedSequences();
return this;
}
/// <summary>
/// Creates a new <see cref="Serializer" /> according to the current configuration.
/// </summary>
public ISerializer Build()
{
return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings);
}
/// <summary>
/// Creates a new <see cref="IValueDeserializer" /> that implements the current configuration.
/// This method is available for advanced scenarios. The preferred way to customize the behavior of the
/// deserializer is to use the <see cref="Build" /> method.
/// </summary>
public IValueSerializer BuildValueSerializer()
{
var typeConverters = BuildTypeConverters();
var typeInspector = BuildTypeInspector();
var traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion);
var eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter());
return new ValueSerializer(
traversalStrategy,
eventEmitter,
typeConverters,
preProcessingPhaseObjectGraphVisitorFactories.Clone(),
emissionPhaseObjectGraphVisitorFactories.Clone()
);
}
internal ITypeInspector BuildTypeInspector()
{
ITypeInspector innerInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties);
if (!ignoreFields)
{
innerInspector = new CompositeTypeInspector(
new ReadableFieldsTypeInspector(typeResolver),
innerInspector
);
}
return typeInspectorFactories.BuildComponentChain(innerInspector);
}
private class ValueSerializer : IValueSerializer
{
private readonly IObjectGraphTraversalStrategy traversalStrategy;
private readonly IEventEmitter eventEmitter;
private readonly IEnumerable<IYamlTypeConverter> typeConverters;
private readonly LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories;
private readonly LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories;
public ValueSerializer(
IObjectGraphTraversalStrategy traversalStrategy,
IEventEmitter eventEmitter,
IEnumerable<IYamlTypeConverter> typeConverters,
LazyComponentRegistrationList<IEnumerable<IYamlTypeConverter>, IObjectGraphVisitor<Nothing>> preProcessingPhaseObjectGraphVisitorFactories,
LazyComponentRegistrationList<EmissionPhaseObjectGraphVisitorArgs, IObjectGraphVisitor<IEmitter>> emissionPhaseObjectGraphVisitorFactories
)
{
this.traversalStrategy = traversalStrategy;
this.eventEmitter = eventEmitter;
this.typeConverters = typeConverters;
this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories;
this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories;
}
public void SerializeValue(IEmitter emitter, object? value, Type? type)
{
var actualType = type ?? (value != null ? value.GetType() : typeof(object));
var staticType = type ?? typeof(object);
var graph = new ObjectDescriptor(value, actualType, staticType);
var preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters);
foreach (var visitor in preProcessingPhaseObjectGraphVisitors)
{
traversalStrategy.Traverse(graph, visitor, default);
}
void NestedObjectSerializer(object? v, Type? t) => SerializeValue(emitter, v, t);
var emittingVisitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain(
new EmittingObjectGraphVisitor(eventEmitter),
inner => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)
);
traversalStrategy.Traverse(graph, emittingVisitor, emitter);
}
}
}
}