对象映射工具 TinyMapper

创建时间:
2016-03-26 00:29
最近更新:
2018-11-10 01:22

2018-11-07 开始使用 TinyMapper

Official Website

TNote: 2018-11-07 已将以下资源中的代码全部整理至 TlTest.Map

Note

  • 网摘: TinyMapper 在 Bind() 时将映射关系保存在一个静态的私有字典中,不需要在每次 Map() 前再次 Bind()

基于 反射 而非 表达式树 实现

2018-11-06 搜索 TinyMapper-3.0.2-beta 源码,发现仅一个 BindingConfigOf.csusing System.Linq.Expressions;

官方文档摘要

Source: TinyMapper: Yet Another Object to Object Mapper for .NET)

from the main body of this article

So you have to do two steps:

  1. Bind source type to the target type
  2. Map source object to the target type

TNote: 对应着 Nelibur.ObjectMapper.TinyMapper 类 中的 Bind()Map(),它们均有 2 个重载。

Note: if you're multithreading an application, register all bindings on application start. While the application is running, you'll call only Map method. So, you'll get speed and thread safe.

TinyMapper can do the first step for you, i.e., you can just call Map and the result will be the same.
Note: Be careful to call Map without Bind, it's not thread safe.
TNote: 上两句等于说 "TinyMapper.Bind<Person, PersonDto>(); 这行代码可以省略、但生产代码中不能省略"。

TinyMapper allows:

  1. Ignore fields
  2. Map one field to a different field
  3. Map interface to exact type

Internally, TinyMapper generates mapping code through ILGenerator. The mapping code looks almost the same as handwritten code.

from Comments and Discussions

Question by visitor

As I understand from your sources, you cache the mappings in internal dictionary, I have two questions about it:

  1. You use normal dictionary, is this thread safety? Most of mattings usually used in web services and API, so thread safety must be the major part for such logic.
  1. You cached by object types, but not by extra mapping rules, so if I define somewhere one mapping rule, but in another place of my app want to redefine it, I will get what?

Answer by author

Yes you're right, TinyMapper caches mappings in internal.

  1. It'll be thread safe if Bind was called only once, i.e. application configure Binding on start (only write to dictionary) and then only Map (only read from the dictionary). Almost all software are done in this manner. So, yes, it's thread safe.
  1. Last will win. Look's like architectural bug if application needs create different kind of mapping for the same types.

For instance:
You've

class Source
{
  public int Id1 {get; set;}
  public int Id2 {get; set;}
}

class Target
{
  public int Id1 {get; set;}
  public int Id2 {get; set;}
}

In one place you've
TinyMapper.Bind<Source, Target>();
and on another place you've
TinyMapper.Bind<Source, Target>(config => config.Ignore(x=>x.Id1));

It's really strange, look's like you've bug in a business logic. You've to create additional NewTarget and create appropriate mapping for it.

Resource

  1. .NET 平台开源项目速览 - 最快的对象映射组件 Tiny Mapper - 几个简单示例
  2. .NET 平台开源项目速览 - 最快的对象映射组件 TinyMapper 之项目实践 - 不知所云
  3. TinyMapper 使用总结