Twinify 1.3.1

dotnet add package Twinify --version 1.3.1
                    
NuGet\Install-Package Twinify -Version 1.3.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Twinify" Version="1.3.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Twinify" Version="1.3.1" />
                    
Directory.Packages.props
<PackageReference Include="Twinify" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Twinify --version 1.3.1
                    
#r "nuget: Twinify, 1.3.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Twinify@1.3.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Twinify&version=1.3.1
                    
Install as a Cake Addin
#tool nuget:?package=Twinify&version=1.3.1
                    
Install as a Cake Tool

Twinify

.NET Support NuGet Version License: MIT

Twinify copies values from one C# object to another. You use it when you have a domain model (for example User) and need a DTO (for example UserDto) without writing a dozen property assignments.

var dto = mapper.Map<UserDto>(user);

That is the whole idea. Everything else is optional: profiles for custom rules, attributes for renames/secrets, and a source generator for Native AOT.


1. Install

In the project that will call Map (your web app, worker, or console):

dotnet add package Twinify
dotnet add package Twinify.DependencyInjection

Twinify.Abstractions is pulled in automatically. You only reference it directly if a class library needs to declare profiles without taking a dependency on the engine.

Supported runtimes: .NET 7, 8, 9, 10, and 11.


2. Your first mapping (5 minutes)

Imagine these two types. Names match, so Twinify can copy them.

public class User
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
}

public class UserDto
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";
}

ASP.NET Core / generic host

In Program.cs:

builder.Services.AddTwinify();

In a service or controller, inject IMapper and map:

using Twinify;

public class UserService(IMapper mapper)
{
    public UserDto ToDto(User user) => mapper.Map<UserDto>(user);
}

AddTwinify() with no profiles means: matching types map by name. No CreateMap required.

Console / tests (no DI)

using Twinify;

var mapper = new Mapper();
var dto = mapper.Map<UserDto>(user);

What gets copied?

Destination member What Twinify does
Same name as a source property (case-insensitive) Copies the value
AddressCity and source has Address.City Flattening: walks the nested path
Extra destination property with no source Left at its default
Extra source property with no destination Ignored
Nested object / List<T> / array Mapped recursively

3. Two ways to configure Twinify

You always inject the same IMapper. You do not change your services to switch modes.

How you register What Map will do
AddTwinify() or new Mapper() Map any matching pair (no profile needed)
AddTwinify(cfg => cfg.AddProfile<UserProfile>()) Only pairs you declared with CreateMap (classic Twinify)
Profiles plus AllowMappingWithoutProfiles() Both: custom CreateMap rules and auto-map other matching DTOs

Nested objects inside a CreateMap still auto-map even when the flag is off. You do not need CreateMap<Address, AddressDto>() just because User has an Address.

Keep your profiles, add one flag

builder.Services.AddTwinify(cfg =>
{
    cfg.AddProfile<UserProfile>();
    cfg.AllowMappingWithoutProfiles();
});

// same thing, chained:
builder.Services.AddTwinify(cfg => cfg.AddProfile<UserProfile>())
    .AllowMappingWithoutProfiles();

CreateMap always wins if both a profile and convention apply to the same pair.


4. When names are not enough: a mapping profile

Use a profile when you need to rename, compute, ignore, or convert a member.

Step 1 — write a profile

using Twinify;

public class UserProfile : MappingProfile
{
    public UserProfile()
    {
        CreateMap<User, UserDto>()
            .ForMember(d => d.FullName, opt => opt.MapFrom(s => $"{s.FirstName} {s.LastName}"))
            .ForMember(d => d.Password, opt => opt.Ignore());
    }
}

Step 2 — register it (same AddTwinify you already have)

builder.Services.AddTwinify(cfg => cfg.AddProfile<UserProfile>());

Step 3 — keep calling Map

public UserDto GetUser(User user) => mapper.Map<UserDto>(user);

Matching properties still copy on their own. You only write ForMember for the exceptions.

Scan an assembly for every MappingProfile instead of listing them:

builder.Services.AddTwinify(typeof(UserProfile).Assembly);

5. Recipes you will actually use

Hide secrets (Password, tokens)

public class UserDto
{
    public int Id { get; set; }
    public string Name { get; set; } = "";

    [IgnoreMap]
    public string? Password { get; set; }
}

Or in a profile: .ForMember(d => d.Password, opt => opt.Ignore()).

Rename / flatten without a profile

public class UserDto
{
    [MapFrom("Address.City")]
    public string Town { get; set; } = "";
}

Nested objects and lists

If User.Address is an Address and UserDto.Address is an AddressDto with the same member names, Twinify maps the nested object. List<Order> → List<OrderDto> works the same way.

Records

public record Person(int Id, string Name);
public record PersonDto(int Id, string Name);

var dto = mapper.Map<PersonDto>(new Person(1, "Ada"));

Twinify binds constructor parameters by name.

Copy onto an existing instance

mapper.Map(user, existingDto);

See why a mapping looks wrong

var explanation = mapper.Explain<User, UserDto>();

Catch bad maps at startup

builder.Services.AddTwinify(cfg => cfg.AddProfile<UserProfile>())
    .ValidateMappings();

Native AOT / trimming

JIT apps (typical ASP.NET) compile maps at runtime. Native AOT cannot do that, so you mark the pair and Twinify generates a static method at compile time:

[Twinify(typeof(User))]
public class UserDto
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
}

Or at assembly scope: [assembly: TwinifyMap(typeof(User), typeof(UserDto))].

On Native AOT, a pair that was not generated throws MappingNotFoundException. ForMember / ConvertUsing are not generated; use [MapFrom] / [IgnoreMap] for AOT, or keep that pair on the JIT runtime.


6. New in 1.3 (.NET 11)

1.3.0 is built and tested against the .NET 11 SDK. Everything below except unions and runtime async also works on .NET 7–10. The source generator now needs the .NET 9 SDK (Roslyn 4.12) or newer; older SDKs skip it with warning CS9057.

C# 15 unions and closed hierarchies

Twinify maps a union or a closed class hierarchy case by case. Each source case is paired with exactly one destination case: same type, then [Twinify(typeof(SourceCase))] / CreateMap, then by name (Cat ↔ CatDto; the suffixes Dto, View, Model, Entity, Response, … are ignored).

public union Pet(Cat, Dog, string);
public union PetDto(CatDto, DogDto, string);

public closed record Shape;
public sealed record Circle(double Radius) : Shape;
public closed record ShapeDto;
public sealed record CircleDto(double Radius) : ShapeDto;

PetDto dto = mapper.Map<Pet, PetDto>(new Cat("Tom", 9));    // dto.Value is CatDto
ShapeDto shape = mapper.Map<Shape, ShapeDto>(new Circle(2)); // CircleDto

Unions and closed types also work as members, inside lists, and as Nullable<TUnion>. If a source case has no destination case, the build fails with TWIN003 (generated maps), ValidateMappings() reports it (runtime maps), and mapping a value of that case throws UnmappedCaseException.

Call-site interceptors

When a Map / MapInto / MapToArray / MapToList call has a generated map for its static types, the generator rewrites that call to invoke the generated method directly. Results are identical: a custom or mocked IMapper still receives the original call. The Twinify package opts you in automatically; turn it off with <TwinifyInterceptors>false</TwinifyInterceptors>.

With <PublishAot>true</PublishAot> (or IsAotCompatible), every statically typed Map call whose pair is not customized in a profile gets a generated map automatically, and the generator warns about the ones it cannot generate, so AOT surprises show up in the IDE instead of production:

Diagnostic Meaning
TWIN001 (warning) This call has no compile-time map and will throw under Native AOT.
TWIN002 (warning) The pair is customized in a profile (ForMember, ConvertUsing, …), which cannot be generated.
TWIN003 (error) A union / closed-hierarchy case has no destination case.
TWIN004 (info) A destination member of a generated map has no source and stays default.

Force the AOT checks on or off with <TwinifyAotDiagnostics>true|false</TwinifyAotDiagnostics>.

Async resolvers

CreateMap<Order, OrderDto>()
    .ForMember(d => d.CustomerName, o => o.MapFromAsync((s, ct) => customers.GetNameAsync(s.CustomerId, ct)))
    .ForMember(d => d.Rating, o => o.MapFromAsync<RatingResolver>()); // IAsyncValueResolver<Order, OrderDto, int>

var dto = await mapper.MapAsync<Order, OrderDto>(order, cancellationToken);

The synchronous Map leaves async members at their default. MapAsync completes synchronously, with no allocation, when a pair has no async members. On .NET 11 Twinify's async path is compiled with runtime async (no state machine is allocated when a resolver suspends, and stack traces stay flat).

Bulk mapping over spans

OrderDto[] array = mapper.MapToArray<Order, OrderDto>(orders);                       // any T[] / span
List<OrderDto> list = mapper.MapToList<Order, OrderDto>(CollectionsMarshal.AsSpan(orderList));
mapper.MapInto<Order, OrderDto>(orders, pooledBuffer.AsSpan(0, orders.Length));       // no allocation besides the DTOs

In compiled maps, simple-member conversions (enum ↔ string, number ↔ string, numeric) no longer box, and enum-to-string reuses one cached string per enum value.


7. If something fails

What you see What it usually means
MappingNotFoundException No CreateMap, convention is off, or Native AOT has no generated map. Add CreateMap, call AllowMappingWithoutProfiles(), or add [Twinify].
Destination member stays default Name mismatch, [IgnoreMap], or the source value was null.
Password appeared on the DTO Add [IgnoreMap] or .Ignore().
Nested object is null Source nested object was null (create maps copy null).
UnmappedCaseException / TWIN003 A union or closed-hierarchy case has no destination case. Add one with a matching name, or [Twinify(typeof(SourceCase))] on the destination case.
TWIN001 / TWIN002 under PublishAot That Map call has no generated map. Declare the pair with [Twinify], or move ForMember rules to [MapFrom] / [IgnoreMap].
Async member is default It was mapped with Map; use MapAsync.

Packages

Package Who references it
Twinify Apps that map. Includes the engine and the source generator.
Twinify.DependencyInjection ASP.NET / generic host: AddTwinify.
Twinify.Abstractions Shared libraries that only declare profiles or attributes.

Contributing

Want to fix a bug or add a feature in Twinify? Read CODE-GUIDE.md — it is written for maintainers: project layout, how a Map call flows, where to change the engine, tests, and invariants you must not break.

Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Twinify:

Package Downloads
Twinify.DependencyInjection

Dependency injection integration for Twinify. Adds AddTwinify(), AddTwinifyProfiles(), ScanForProfiles(), EnableConventionMaps() / AllowMappingWithoutProfiles(), and ValidateMappings() for IServiceCollection. AddTwinify() with no profiles maps matching DTOs by convention. With AddProfile, add AllowMappingWithoutProfiles() to also map undeclared pairs without changing how IMapper is injected.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.3.1 121 11/24/2026
1.3.0 124 11/12/2026
1.2.0-rc.2 60 11/4/2026
1.2.0-rc.1 72 11/4/2026
1.1.0 169 9/14/2026
1.0.2 145 8/7/2026
1.0.1 129 8/7/2026
1.0.0 156 7/13/2026