using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Luticate2.Auth.Utils.Dbo; using Luticate2.Auth.Utils.Dbo.Result; using Luticate2.Auth.Utils.Interfaces; namespace Luticate2.Auth.Utils.Business.Converters { public class LuConvertersAllocator : ILuConvertersAllocator { protected static IDictionary listTypes = new Dictionary { {typeof(IEnumerable<>), typeof(List<>)}, {typeof(ICollection<>), typeof(Collection<>)}, {typeof(Collection<>), typeof(Collection<>)}, {typeof(IList<>), typeof(List<>)}, {typeof(List<>), typeof(List<>)} }; public virtual LuResult CreateInstance(Type type) { try { var obj = Activator.CreateInstance(type); // TODO Nullable (and maybe others) gets null instead of object // if (obj != null) // { return LuResult.Ok(obj); // } // return LuResult.Error(LuStatus.InternalError.ToInt(), // $"Could not instantiate type {type}"); } catch (Exception e) { return LuResult.Error(LuStatus.InternalError.ToInt(), e); } } public virtual LuResult GetInstance(Type type) { if (type.IsGenericType) { var gtype = type.GetGenericTypeDefinition(); if (listTypes.ContainsKey(gtype)) { var glistType = listTypes[gtype].MakeGenericType(type.GenericTypeArguments[0]); var listActivateResult = CreateInstance(glistType); return listActivateResult; } } if (type == typeof(string)) { return LuResult.Ok(""); } var activateResult = CreateInstance(type); return activateResult; } } }