byme8 / AOTMapper

Experimental implementation of library like AutoMapper powered by Roslyn code generation.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

AOTMapper

The experimental mapper library that helps to manage your mappers.

Get started

Let's suppose you have a following models in your project and we want to make a mapper for them:

// Somewhere in your project
public class User 
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class UserEntity
{
    public string Name { get; set; }
    public int Age { get; set; }
}

First of all, we need to install nuget package to our project:

dotnet add package AOTMapper

Now we can declare our mapper method like that:

public static class UserMapper
{
    [AOTMapperMethod]
    public static User MapToUser(this IAOTMapper, UserEntity input)
    {
        var output = new User();
        output.Name = input.Name;
        output.Age = input.Age;

        return output;
    }
}

Now we can create our mapper instance and use it:

var mapper = new AOTMapperBuilder()
    .AddTestProject() // magic extension method, we will talk about it later
    .Build();

var entity = new UserEntity
{
    Name = "John",
    Age = 30
};

var user = mapper.Map<User>(entity);

Console.WriteLine(user.Name); // John
Console.WriteLine(user.Age); // 30

Done! Everything is mapped and ready to go.

Now let's talk about the magic extension method and how it works in general. The 'AddTestProject' is generated by the special source generator. The source generator looks around for [AOTMapperMethod] attributes. Then, for each assembly, it generates extenstion method that adds mapper method to AOTMapperBuilder:

public static AOTMapperBuilder AddTestProject(this AOTMapperBuilder builder)
{
    builder.AddMapper<global::TestProject.UserEntity, global::TestProject.User>(global::TestProject.UserMapper.MapToUser);

    return builder;
}

About

Experimental implementation of library like AutoMapper powered by Roslyn code generation.

License:MIT License


Languages

Language:C# 92.7%Language:PowerShell 7.3%