You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LuObjectConverterPoco.cs 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using Luticate2.Auth.Utils.Business.Fields;
  3. using Luticate2.Auth.Utils.Business.Utils;
  4. using Luticate2.Auth.Utils.Dbo.Fields;
  5. using Luticate2.Auth.Utils.Dbo.Result;
  6. using Luticate2.Auth.Utils.Interfaces;
  7. using Microsoft.Extensions.DependencyInjection;
  8. namespace Luticate2.Auth.Utils.Business.ObjectConverter
  9. {
  10. public class LuObjectConverterPoco<TTypeFrom, TTypeTo> : ILuObjectConverter<TTypeFrom, TTypeTo>
  11. {
  12. protected IServiceProvider ServiceProvider { get; }
  13. public LuObjectConverterPoco(IServiceProvider serviceProvider)
  14. {
  15. ServiceProvider = serviceProvider;
  16. }
  17. public LuResult<object> Convert(object srcObj, object dstObj, LuFieldDbo path, LuPartialFieldsDbo fields, ILuObjectConverterOptions options)
  18. {
  19. if (srcObj == null)
  20. {
  21. return LuResult<object>.Ok(default(TTypeTo));
  22. }
  23. // TODO Handle descriptor == null
  24. var descriptor = ServiceProvider.GetService<ILuObjectConverterDescriptor<TTypeTo, TTypeFrom>>();
  25. var typeTo = typeof(TTypeTo);
  26. // var dstObj = options.Allocator.GetInstance(typeTo);
  27. foreach (var memberInfo in typeTo.GetProperties())
  28. {
  29. var memberPath = LuFieldDbo.Make(path).Add(memberInfo.Name);
  30. if (!fields.Fields.IsIncluded(memberPath))
  31. {
  32. continue;
  33. }
  34. // TODO Handle srcPropExpression == null
  35. var subSrcPropExpression = descriptor.GetMemberValueExpression(memberInfo, options.DescriptorOptions);
  36. var subSrcPropDelegate = subSrcPropExpression.Compile();
  37. var subSrcProp = subSrcPropDelegate.DynamicInvoke(srcObj);
  38. var subSrcType = subSrcProp != null ? subSrcProp.GetType() : subSrcPropExpression.ReturnType;
  39. var subDstType = memberInfo.GetUnderlyingType();
  40. // TODO Handle objectConverter == null
  41. var objectConverter = LuObjectConverterUtils.GetObjectConverter(ServiceProvider, subSrcType, subDstType);
  42. var subDstObj = options.Allocator.GetInstance(subDstType);
  43. var dstPropResult = objectConverter.Convert(subSrcProp, subDstObj, memberPath, fields, options);
  44. if (!dstPropResult)
  45. {
  46. return dstPropResult;
  47. }
  48. var dstProp = dstPropResult.Data;
  49. var result = LuExpressionUtils.SetValueFromMember(memberInfo, dstObj, dstProp);
  50. if (!result)
  51. {
  52. return result.To<object>();
  53. }
  54. }
  55. return LuResult<object>.Ok(dstObj);
  56. }
  57. }
  58. }