12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- 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<Type, Type> listTypes = new Dictionary<Type, Type>
- {
- {typeof(IEnumerable<>), typeof(List<>)},
- {typeof(ICollection<>), typeof(Collection<>)},
- {typeof(Collection<>), typeof(Collection<>)},
- {typeof(IList<>), typeof(List<>)},
- {typeof(List<>), typeof(List<>)}
- };
-
- public virtual LuResult<object> CreateInstance(Type type)
- {
- try
- {
- var obj = Activator.CreateInstance(type);
- // TODO Nullable<T> (and maybe others) gets null instead of object
- // if (obj != null)
- // {
- return LuResult<object>.Ok(obj);
- // }
-
- // return LuResult<object>.Error(LuStatus.InternalError.ToInt(),
- // $"Could not instantiate type {type}");
- }
- catch (Exception e)
- {
- return LuResult<object>.Error(LuStatus.InternalError.ToInt(), e);
- }
- }
-
- public virtual LuResult<object> 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<object>.Ok("");
- }
-
- var activateResult = CreateInstance(type);
- return activateResult;
- }
- }
- }
|