Facet.Mapping
2.3.0
dotnet add package Facet.Mapping --version 2.3.0
NuGet\Install-Package Facet.Mapping -Version 2.3.0
<PackageReference Include="Facet.Mapping" Version="2.3.0" />
<PackageVersion Include="Facet.Mapping" Version="2.3.0" />
<PackageReference Include="Facet.Mapping" />
paket add Facet.Mapping --version 2.3.0
#r "nuget: Facet.Mapping, 2.3.0"
#:package Facet.Mapping@2.3.0
#addin nuget:?package=Facet.Mapping&version=2.3.0
#tool nuget:?package=Facet.Mapping&version=2.3.0
Facet.Mapping
Facet.Mapping enables advanced static mapping logic for the Facet source generator.
This package defines strongly-typed interfaces that allow you to plug in custom mapping logic between source and generated Facet types with support for both synchronous and asynchronous operations, dependency injection, all at compile time with zero runtime reflection.
What is this for?
Facet
lets you define slim, redacted, or projected versions of classes using just attributes.
With Facet.Mapping, you can go further and define custom logic like combining properties, renaming, transforming types, applying conditions, or performing async operations like database lookups and API calls.
How it works
Static Mappers (No Dependencies)
- Implement the
IFacetMapConfiguration<TSource, TTarget>
interface. - Define a static
Map
method. - Point the
[Facet(...)]
attribute to the config class usingConfiguration = typeof(...)
.
Instance Mappers (With Dependency Injection)
- Implement the
IFacetMapConfigurationAsyncInstance<TSource, TTarget>
interface. - Define an instance
MapAsync
method. - Use the new extension methods that accept mapper instances.
Synchronous Mapping
- Implement
IFacetMapConfiguration<TSource, TTarget>
(static) orIFacetMapConfigurationInstance<TSource, TTarget>
(instance). - Define a
Map
method.
Asynchronous Mapping
- Implement
IFacetMapConfigurationAsync<TSource, TTarget>
(static) orIFacetMapConfigurationAsyncInstance<TSource, TTarget>
(instance). - Define a
MapAsync
method. - Use the async extension methods to perform mapping operations.
Hybrid Mapping
- Implement
IFacetMapConfigurationHybrid<TSource, TTarget>
(static) orIFacetMapConfigurationHybridInstance<TSource, TTarget>
(instance). - Define both
Map
andMapAsync
methods for optimal performance.
Install
dotnet add package Facet.Mapping
Examples
Basic Synchronous Mapping (Static)
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Id { get; set; }
}
[Facet(typeof(User), GenerateConstructor = true, Configuration = typeof(UserMapper))]
public partial class UserDto
{
public string FullName { get; set; }
public int Id { get; set; }
}
public class UserMapper : IFacetMapConfiguration<User, UserDto>
{
public static void Map(User source, UserDto target)
{
target.FullName = $"{source.FirstName} {source.LastName}";
}
}
Asynchronous Mapping
public class User
{
public string Email { get; set; }
public int Id { get; set; }
}
[Facet(typeof(User))]
public partial class UserDto
{
public string Email { get; set; }
public int Id { get; set; }
public string ProfilePicture { get; set; }
public decimal ReputationScore { get; set; }
}
public class UserAsyncMapper : IFacetMapConfigurationAsync<User, UserDto>
{
public static async Task MapAsync(User source, UserDto target, CancellationToken cancellationToken = default)
{
// Async database lookup (limited - no DI)
target.ProfilePicture = await GetProfilePictureAsync(source.Id, cancellationToken);
// Async API call (limited - no DI)
target.ReputationScore = await CalculateReputationAsync(source.Email, cancellationToken);
}
private static async Task<string> GetProfilePictureAsync(int userId, CancellationToken cancellationToken)
{
// Simple implementation without DI
await Task.Delay(100, cancellationToken);
return $"https://api.example.com/users/{userId}/avatar.jpg";
}
private static async Task<decimal> CalculateReputationAsync(string email, CancellationToken cancellationToken)
{
await Task.Delay(50, cancellationToken);
return Random.Shared.Next(1, 6) + (decimal)Random.Shared.NextDouble();
}
}
// Usage
var userDto = await user.ToFacetAsync<User, UserDto, UserAsyncMapper>();
Asynchronous Mapping with Dependency Injection
// Define your services
public interface IProfilePictureService
{
Task<string> GetProfilePictureAsync(int userId, CancellationToken cancellationToken = default);
}
public interface IReputationService
{
Task<decimal> CalculateReputationAsync(string email, CancellationToken cancellationToken = default);
}
// Implement services with real dependencies (DbContext, HttpClient, etc.)
public class ProfilePictureService : IProfilePictureService
{
private readonly IDbContext _dbContext;
private readonly ILogger<ProfilePictureService> _logger;
public ProfilePictureService(IDbContext dbContext, ILogger<ProfilePictureService> logger)
{
_dbContext = dbContext;
_logger = logger;
}
public async Task<string> GetProfilePictureAsync(int userId, CancellationToken cancellationToken = default)
{
try
{
var user = await _dbContext.Users.FindAsync(userId, cancellationToken);
return user?.ProfilePictureUrl ?? "/images/default-avatar.png";
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to load profile picture for user {UserId}", userId);
return "/images/default-avatar.png";
}
}
}
// Instance mapper with dependency injection
public class UserAsyncMapperWithDI : IFacetMapConfigurationAsyncInstance<User, UserDto>
{
private readonly IProfilePictureService _profilePictureService;
private readonly IReputationService _reputationService;
public UserAsyncMapperWithDI(IProfilePictureService profilePictureService, IReputationService reputationService)
{
_profilePictureService = profilePictureService;
_reputationService = reputationService;
}
public async Task MapAsync(User source, UserDto target, CancellationToken cancellationToken = default)
{
// Use injected services for real implementations
target.ProfilePicture = await _profilePictureService.GetProfilePictureAsync(source.Id, cancellationToken);
target.ReputationScore = await _reputationService.CalculateReputationAsync(source.Email, cancellationToken);
}
}
// Register in DI container
services.AddScoped<IProfilePictureService, ProfilePictureService>();
services.AddScoped<IReputationService, ReputationService>();
services.AddScoped<UserAsyncMapperWithDI>();
// Usage with DI
public class UserController : ControllerBase
{
private readonly UserAsyncMapperWithDI _userMapper;
public UserController(UserAsyncMapperWithDI userMapper)
{
_userMapper = userMapper;
}
[HttpGet("{id}")]
public async Task<UserDto> GetUser(int id)
{
var user = await GetUserFromDatabase(id);
// NEW: Use instance mapper with injected dependencies
return await user.ToFacetAsync(_userMapper);
}
[HttpGet]
public async Task<List<UserDto>> GetUsers()
{
var users = await GetUsersFromDatabase();
// NEW: Collection mapping with DI support
return await users.ToFacetsParallelAsync(_userMapper, maxDegreeOfParallelism: 4);
}
}
NEW: Hybrid Mapping with Dependency Injection
public class UserHybridMapperWithDI : IFacetMapConfigurationHybridInstance<User, UserDto>
{
private readonly IProfilePictureService _profilePictureService;
private readonly IReputationService _reputationService;
public UserHybridMapperWithDI(IProfilePictureService profilePictureService, IReputationService reputationService)
{
_profilePictureService = profilePictureService;
_reputationService = reputationService;
}
// Fast synchronous operations
public void Map(User source, UserDto target)
{
target.FullName = $"{source.FirstName} {source.LastName}";
target.Email = source.Email.ToLower();
}
// Expensive asynchronous operations with injected services
public async Task MapAsync(User source, UserDto target, CancellationToken cancellationToken = default)
{
target.ProfilePicture = await _profilePictureService.GetProfilePictureAsync(source.Id, cancellationToken);
target.ReputationScore = await _reputationService.CalculateReputationAsync(source.Email, cancellationToken);
}
}
// Usage
var userDto = await user.ToFacetHybridAsync(hybridMapperWithDI);
When to Use Each Approach
Scenario | Recommended Approach | Interface |
---|---|---|
Simple property transformations | Static mapper | IFacetMapConfiguration<TSource, TTarget> |
Complex logic with external services | Instance mapper | IFacetMapConfigurationAsyncInstance<TSource, TTarget> |
Database operations | Instance mapper with DbContext | IFacetMapConfigurationAsyncInstance<TSource, TTarget> |
HTTP API calls | Instance mapper with HttpClient | IFacetMapConfigurationAsyncInstance<TSource, TTarget> |
Logging and error handling | Instance mapper with ILogger | IFacetMapConfigurationAsyncInstance<TSource, TTarget> |
Mixed sync/async operations | Hybrid instance mapper | IFacetMapConfigurationHybridInstance<TSource, TTarget> |
Benefits of Instance Mappers
Dependency Injection Support
- Inject any service:
IDbContext
,IHttpClient
,ILogger
, custom services - Full integration with DI containers (ASP.NET Core, etc.)
- Easy to configure and manage dependencies
Better Testability
- Mock dependencies for unit testing
- Isolate mapper logic from external services
- Test different scenarios with different service implementations
Real-World Integration
- Access to properly configured services
- Connection string management through DI
- Shared service instances and connection pooling
Error Handling and Logging
- Inject
ILogger
for proper logging - Structured error handling with context
- Integration with application monitoring
Backward Compatibility
- All existing static mappers continue to work unchanged
- Gradual migration path
- Choose the right tool for each scenario
Facet.Mapping � Simple transformations with static mappers, complex scenarios with dependency injection.
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | 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 was computed. 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. |
-
net8.0
- No dependencies.
-
net9.0
- No dependencies.
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
Version | Downloads | Last Updated |
---|---|---|
2.3.0 | 12 | 8/20/2025 |
2.2.0 | 13 | 8/20/2025 |
2.1.0 | 22 | 8/18/2025 |
2.0.1 | 235 | 8/5/2025 |
2.0.0 | 146 | 8/4/2025 |
1.9.3 | 114 | 7/4/2025 |
1.8.0 | 141 | 6/4/2025 |
1.7.0 | 159 | 5/6/2025 |
1.6.0 | 134 | 4/27/2025 |
1.5.0 | 104 | 4/26/2025 |
1.4.0 | 138 | 4/25/2025 |
1.3.0 | 168 | 4/24/2025 |
1.2.0 | 158 | 4/24/2025 |
1.1.1 | 169 | 4/23/2025 |
1.1.0 | 155 | 4/23/2025 |
1.0.0 | 160 | 4/23/2025 |