//
// 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 System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using NosSmooth.Packets.Converters.Special.Converters;
using NosSmooth.Packets.Errors;
using NosSmooth.Packets.Extensions;
using NosSmooth.PacketSerializer.Abstractions;
using Remora.Results;
namespace NosSmooth.Packets.Converters.Special;
///
/// Converts lists.
///
public class ListStringConverterFactory : IStringConverterFactory
{
private readonly IServiceProvider _serviceProvider;
///
/// Initializes a new instance of the class.
///
/// The service provider.
public ListStringConverterFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
///
public bool ShouldHandle(Type type)
=> type.IsGenericType && typeof(IEnumerable).IsAssignableFrom(type);
///
public Result CreateTypeSerializer(Type type)
{
var elementType = type.GetElementType() ?? type.GetGenericArguments()[0];
var converterType = typeof(ListStringConverter<>).MakeGenericType(elementType);
try
{
return Result
.FromSuccess((IStringConverter)ActivatorUtilities.CreateInstance(_serviceProvider, converterType));
}
catch (Exception e)
{
return e;
}
}
///
public Result> CreateTypeSerializer()
=> CreateTypeSerializer(typeof(T)).Cast, IStringConverter>();
}