| | 1 | | using System.Text.Json; |
| | 2 | | using System.Text.Json.Serialization; |
| | 3 | |
|
| | 4 | | namespace Common.Core.Classes; |
| | 5 | |
|
| | 6 | | /// <summary>Initializes a new instance of the InterfaceFactory class.</summary> |
| | 7 | | /// <param name="concrete">The concrete class type.</param> |
| | 8 | | /// <param name="interfaceType">The interface type.</param> |
| | 9 | | /// <remarks>Supports converting Interface types for Json serialization by using a factory pattern.</remarks> |
| 4 | 10 | | public class InterfaceFactory( Type concrete, Type interfaceType ) : JsonConverterFactory |
| | 11 | | { |
| | 12 | | #region Properties |
| | 13 | |
|
| | 14 | | /// <summary>Gets the concrete class type.</summary> |
| 5 | 15 | | public Type ConcreteType { get; } = concrete; |
| | 16 | |
|
| | 17 | | /// <summary>Gets the interface type.</summary> |
| 6 | 18 | | public Type InterfaceType { get; } = interfaceType; |
| | 19 | |
|
| | 20 | | #endregion |
| | 21 | |
|
| | 22 | | #region Overridden Methods |
| | 23 | |
|
| | 24 | | /// <summary>Determines whether the converter instance can convert the specified object type.</summary> |
| | 25 | | /// <param name="typeToConvert">The type of the object to check whether it can be |
| | 26 | | /// converted by this converter instance.</param> |
| | 27 | | /// <returns><see langword="true"/> if the instance can convert the specified object type otherwise |
| | 28 | | /// <see langword="false"/>.</returns> |
| | 29 | | public override bool CanConvert( Type typeToConvert ) |
| 1 | 30 | | { |
| 1 | 31 | | return typeToConvert == InterfaceType; |
| 1 | 32 | | } |
| | 33 | |
|
| | 34 | | /// <summary>Creates a converter for a specified type.</summary> |
| | 35 | | /// <param name="typeToConvert">The type handled by the converter.</param> |
| | 36 | | /// <param name="options">The serialization options to use.</param> |
| | 37 | | /// <returns>A converter compatible with typeToConvert.</returns> |
| | 38 | | public override JsonConverter CreateConverter( Type typeToConvert, JsonSerializerOptions options ) |
| 1 | 39 | | { |
| 1 | 40 | | var converterType = typeof( InterfaceConverter<,> ).MakeGenericType( ConcreteType, InterfaceType ); |
| | 41 | |
|
| 1 | 42 | | return (JsonConverter)Activator.CreateInstance( converterType )!; |
| 1 | 43 | | } |
| | 44 | |
|
| | 45 | | #endregion |
| | 46 | | } |