Home

Awesome

LightweightObjectMapper

1. Intro

A out of the box object mapper library based on SourceGenerator. 基于 SourceGenerator 的开箱即用对象映射库。

2. Features

Note!!!

3. 使用方法

3.1 引用包

<ItemGroup>
  <PackageReference Include="LightweightObjectMapper" Version="1.0.0" />
</ItemGroup>

3.2 快速使用

无配置文件的使用方式,引用命名空间 LightweightObjectMapper ,直接使用拓展方法 MapTo 进行映射;

using LightweightObjectMapper;

class Class1 { }
class Class2 { }
struct Struct1 { }

class1Instance.MapTo<Class2>();
class1Instance.MapTo(class2Instance);

class1Instance.MapTo(ref struct1Instance);

var list1 = new List<Class1>();
list1.MapTo<IEnumerable<Class2>>();

3.3 配置映射 MappingProfile

using System.Collections.Concurrent;
using System.Collections.Generic;
using LightweightObjectMapper;

namespace MappingProfileSample;

class MyClass1
{
   public int MyProperty1 { get; set; }

   public int MyProperty2 { get; set; }

   public int MyProperty3 { get; set; }
}

class MyClass2
{
   public int MyProperty1 { get; set; }

   public int MyProperty2 { get; set; }

   public int MyProperty3 { get; set; }
}

[MappingProfile]
internal partial class SampleMappingProfile
   : IMappingPrepare<MyClass1, MyClass2>
   , IPostMapping<MyClass1, MyClass2>
   , ITypeMapping<MyClass2, MyClass1>
   , ITypeMemberIgnoreMapping<MyClass2>
{
   public object? IgnoreMapping(MyClass2 target)
   {
       // 映射到 MyClass2 时忽略其 MyProperty2
       return new
       {
           target.MyProperty2,
       };
   }

   public MyClass2 MappingPrepare(MyClass1 source)
   {
       // MyClass1 映射到 MyClass2 时,MyClass2 实例的创建方式
       return new MyClass2()
       {
           MyProperty1 = 1
       };
   }

   public MyClass2 PostMapping(MyClass1 source, MyClass2 target)
   {
       // MyClass1 映射到 MyClass2 时,映射完成后执行的代码
       target.MyProperty1 = source.MyProperty1 * 2;
       return target;
   }

   public MyClass1 TypeMapping(MyClass2 source)
   {
       //接管 MyClass2 到 MyClass1 的映射
       return new MyClass1()
       {
           MyProperty1 = source.MyProperty1 / 2
       };
   }

   [CollectionMapping]
   public static ConcurrentBag<T>? ToList<T>(IEnumerable<T>? items)
   {
       //拓展对 ConcurrentBag 的映射支持
       return items is null ? null : new ConcurrentBag<T>(items);
   }
}

3.4 引入其它程序集内的 MappingProfile

跨程序集共享 MappingProfile

// 引用 InternalMappingProfile 和 InternalMappingProfile1
[MappingProfileInclude(typeof(InternalMappingProfile), typeof(InternalMappingProfile1))]
[MappingProfile]
internal partial class MappingProfileIncludeMapProfile1
{
}

4. 其它配置

配置项目的 Property 来进行一些特殊配置,示例:

  <PropertyGroup>
    <!--不添加预生成代码-->
    <NoLightweightObjectMapperPreCodes>true</NoLightweightObjectMapperPreCodes>
    <!--设置生成的拓展方法可访问性-->
    <LOMappingMethodAccessibility>public</LOMappingMethodAccessibility>
  </PropertyGroup>