~ruther/NosSmooth

ref: 79b27514e7c8b729701aff24c294329b5f7483d2 NosSmooth/Packets/NosSmooth.PacketSerializer/Converters/Special/ListStringConverterFactory.cs -rw-r--r-- 1.8 KiB
79b27514 — Rutherther chore: move PacketSerializer types to correct namespace 2 years ago
                                                                                
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
//
//  ListStringConverterFactory.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Collections;
using Microsoft.Extensions.DependencyInjection;
using NosSmooth.PacketSerializer.Abstractions;
using NosSmooth.PacketSerializer.Converters.Special.Converters;
using Remora.Results;

namespace NosSmooth.PacketSerializer.Converters.Special;

/// <summary>
/// Converts lists.
/// </summary>
public class ListStringConverterFactory : IStringConverterFactory
{
    private readonly IServiceProvider _serviceProvider;

    /// <summary>
    /// Initializes a new instance of the <see cref="ListStringConverterFactory"/> class.
    /// </summary>
    /// <param name="serviceProvider">The service provider.</param>
    public ListStringConverterFactory(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    /// <inheritdoc />
    public bool ShouldHandle(Type type)
        => type.IsGenericType && typeof(IEnumerable).IsAssignableFrom(type);

    /// <inheritdoc />
    public Result<IStringConverter> CreateTypeSerializer(Type type)
    {
        var elementType = type.GetElementType() ?? type.GetGenericArguments()[0];
        var converterType = typeof(ListStringConverter<>).MakeGenericType(elementType);
        try
        {
            return Result<IStringConverter>
                .FromSuccess((IStringConverter)ActivatorUtilities.CreateInstance(_serviceProvider, converterType));
        }
        catch (Exception e)
        {
            return e;
        }
    }

    /// <inheritdoc />
    public Result<IStringConverter<T>> CreateTypeSerializer<T>()
        => CreateTypeSerializer(typeof(T)).Cast<IStringConverter<T>, IStringConverter>();
}
Do not follow this link