Overview
Object mapping transfers data from one object type to another according to predefined rules, reducing manual mapping code and human error — for example, mapping a DTO to an Entity and vice versa.
Silky supports two object mapping tools:
| Tool | NuGet Package | Notes |
|---|---|---|
| AutoMapper | Silky.ObjectMapper.AutoMapper | Industry-standard, feature-rich (included in Silky.Agent.Host) |
| Mapster | Silky.ObjectMapper.Mapster | High-performance, supports code generation |
AutoMapper
Step 1: Depend on AutoMapperModule
If you use DefaultWebHostModule, DefaultGeneralHostModule, or other built-in modules, AutoMapperModule is already included. For custom startup modules, declare the dependency explicitly:
[DependsOn(
typeof(AutoMapperModule),
typeof(DotNettyTcpModule),
)]
public class CustomHostModule : GeneralHostModule
{
}
Step 2: Define a Profile
public class AccountProfile : Profile
{
public AccountProfile()
{
// DTO → Entity
CreateMap<CreateAccountInput, Account>();
// Entity → DTO
CreateMap<Account, GetAccountOutput>();
// With custom logic
CreateMap<UpdateAccountInput, Account>()
.AfterMap((src, dest) =>
{
dest.UpdateTime = DateTime.Now;
});
}
}
Step 3: Use MapTo Extension Method
public async Task<GetAccountOutput> CreateAsync(CreateAccountInput input)
{
var account = input.MapTo<Account>();
account = await _accountDomainService.CreateAsync(account);
return account.MapTo<GetAccountOutput>();
}
Mapster
Installation
<PackageReference Include="Silky.ObjectMapper.Mapster" Version="3.9.2" />
Register Mapster
[DependsOn(typeof(MapsterModule))]
public class CustomHostModule : GeneralHostModule { }
Usage
Mapster works without configuration for simple type pairs. For custom rules:
TypeAdapterConfig<CreateAccountInput, Account>
.NewConfig()
.Map(dest => dest.CreatedTime, src => DateTime.Now);
Use the same MapTo<T>() extension method — Silky abstracts the underlying mapping tool:
var account = input.MapTo<Account>();
var output = account.MapTo<GetAccountOutput>();
MapTo vs Manual Mapping
| Approach | Code | Maintenance |
|---|---|---|
MapTo<T>() | One line per conversion | Profile-based, easy to change |
| Manual assignment | N lines per property | Error-prone, tedious |
Use MapTo<T>() for standard property name matches. Use custom Profile rules for complex transformations (rename, computed fields, nested objects).
