AdaskoTheBeAsT.AutoMapper.SimpleInjector
15.0.0
dotnet add package AdaskoTheBeAsT.AutoMapper.SimpleInjector --version 15.0.0
NuGet\Install-Package AdaskoTheBeAsT.AutoMapper.SimpleInjector -Version 15.0.0
<PackageReference Include="AdaskoTheBeAsT.AutoMapper.SimpleInjector" Version="15.0.0" />
<PackageVersion Include="AdaskoTheBeAsT.AutoMapper.SimpleInjector" Version="15.0.0" />
<PackageReference Include="AdaskoTheBeAsT.AutoMapper.SimpleInjector" />
paket add AdaskoTheBeAsT.AutoMapper.SimpleInjector --version 15.0.0
#r "nuget: AdaskoTheBeAsT.AutoMapper.SimpleInjector, 15.0.0"
#:package AdaskoTheBeAsT.AutoMapper.SimpleInjector@15.0.0
#addin nuget:?package=AdaskoTheBeAsT.AutoMapper.SimpleInjector&version=15.0.0
#tool nuget:?package=AdaskoTheBeAsT.AutoMapper.SimpleInjector&version=15.0.0
AdaskoTheBeAsT.AutoMapper.SimpleInjector
Seamless AutoMapper integration for SimpleInjector with automatic registration and configuration
Why Use This?
This library eliminates the boilerplate of manually registering AutoMapper with SimpleInjector. It automatically:
- 🔍 Scans assemblies for
Profileclasses and registers them - 🔄 Auto-registers all AutoMapper extensions (
ITypeConverter,IValueResolver,IMemberValueResolver,IValueConverter,IDestinationFactory,ICondition,IPreCondition,IMappingAction) - 💉 Handles dependency injection for your custom converters and resolvers
- ⚙️ Configures everything with a single fluent API call
- 🎯 Targets .NET 10 and .NET 11
Installation
dotnet add package AdaskoTheBeAsT.AutoMapper.SimpleInjector
1. Create Your Mapping Profiles
using AutoMapper;
public sealed record UserEntity(int Id, string Name);
public sealed record UserDto(int Id, string Name);
public class UserProfile : Profile
{
public UserProfile()
{
CreateMap<UserEntity, UserDto>();
CreateMap<UserDto, UserEntity>();
}
}
2. Register AutoMapper with SimpleInjector
Register an ILoggerFactory before resolving the mapper. Use your application's
logger factory, or use NullLoggerFactory for a console example that does not need
logging. Set AUTOMAPPER_LICENSE_KEY in the application's environment (see
Setting the AutoMapper License Key).
using AdaskoTheBeAsT.AutoMapper.SimpleInjector;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using SimpleInjector;
using var container = new Container();
container.RegisterInstance<ILoggerFactory>(NullLoggerFactory.Instance);
// Scan the assembly containing UserProfile.
container.AddAutoMapper(typeof(UserProfile));
3. Use IMapper in Your Services
using AutoMapper;
public class UserService
{
private readonly IMapper _mapper;
public UserService(IMapper mapper)
{
_mapper = mapper;
}
public UserDto GetUser(UserEntity entity)
{
return _mapper.Map<UserDto>(entity);
}
}
Add this to your container setup after AddAutoMapper:
container.Register<UserService>();
container.Verify();
var service = container.GetInstance<UserService>();
var dto = service.GetUser(new UserEntity(1, "Ada"));
Console.WriteLine(dto.Name); // Ada
What Gets Registered?
This library automatically registers the following with your container:
| Type | Registration | Description |
|---|---|---|
IConfigurationProvider |
Singleton | AutoMapper configuration (not registered when using custom mapper instance) |
IMapper |
Singleton* | Main mapper instance |
ITypeConverter<,> |
Transient | Custom type converters |
IValueConverter<,> |
Transient | Custom value converters |
IValueResolver<,,> |
Transient | Custom value resolvers |
IMemberValueResolver<,,,> |
Transient | Custom member resolvers |
IDestinationFactory<,> |
Transient | Custom destination object factories (ConstructUsing<T>()) |
ICondition<,,> |
Transient | Custom member conditions (Condition<T>()) |
IPreCondition<,> |
Transient | Custom member pre-conditions (PreCondition<T>()) |
IMappingAction<,> |
Transient | Custom mapping actions |
*Lifestyle is configurable (Singleton/Scoped/Transient)
Usage Examples
Each registration example is an alternative to the quick start's AddAutoMapper
call. Use one per container.
Basic Usage - Scan by Type
container.AddAutoMapper(typeof(UserProfile), typeof(OrderProfile));
Scan an Explicit List of Assemblies
container.AddAutoMapper(typeof(UserProfile).Assembly, typeof(OrderProfile).Assembly);
Using Custom Resolvers with Dependency Injection
Register the resolver's dependencies in SimpleInjector and configure the member
with MapFrom<TResolver>(). The resolver must be in a scanned assembly.
using AutoMapper;
public class ResolverProfile : Profile
{
public ResolverProfile()
{
CreateMap<Source2, Dest2>()
.ForMember(d => d.ResolvedValue, opt => opt.MapFrom<DependencyResolver>());
}
}
public class DependencyResolver(ISomeService service) : IValueResolver<Source2, Dest2, int>
{
public int Resolve(Source2 source, Dest2 destination, int destMember, ResolutionContext context)
{
return service.Modify(source.Value);
}
}
For example, if FooService(5) adds 5 to its input:
container.Register<ISomeService>(() => new FooService(5), Lifestyle.Transient);
container.AddAutoMapper(typeof(ResolverProfile));
var mapper = container.GetInstance<AutoMapper.IMapper>();
var dest = mapper.Map<Dest2>(new Source2 { Value = 10 });
Console.WriteLine(dest.ResolvedValue); // 15
See the complete console sample. Set AUTOMAPPER_LICENSE_KEY
in your environment before running it. From the repository root:
dotnet run --project samples/TestApp --framework net11.0
The sample prints Mapped value: 7 and Resolved value: 15. Use
--framework net10.0 to run it on .NET 10.
Advanced Configuration
Change IMapper Lifestyle (Scoped/Transient)
For a scoped mapper, set the default scoped lifestyle before the first container
registration. Resolve IMapper inside an active scope. The default mapper
lifestyle is singleton; use AsTransient() for a new mapper on each resolution.
using AdaskoTheBeAsT.AutoMapper.SimpleInjector;
using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using SimpleInjector;
using SimpleInjector.Lifestyles;
using var container = new Container();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.RegisterInstance<ILoggerFactory>(NullLoggerFactory.Instance);
container.AddAutoMapper(cfg =>
{
cfg.WithMapperAssemblyMarkerTypes(typeof(UserProfile));
cfg.AsScoped();
});
using var scope = AsyncScopedLifestyle.BeginScope(container);
var mapper = container.GetInstance<IMapper>();
var dto = mapper.Map<UserDto>(new UserEntity(1, "Ada"));
Custom Mapper Configuration
Add custom mappings programmatically:
container.AddAutoMapper(cfg =>
{
cfg.WithAssembliesToScan(assemblies);
cfg.WithMapperConfigurationExpressionAction((_, expression) =>
{
// Add custom mappings
expression.CreateMap<Foo, Bar>().ReverseMap();
// Configure global settings
expression.AllowNullCollections = true;
});
});
Using Custom IMapper Implementation
If you already have a custom type that implements IMapper, register it with
Using<TMapper>(). AutoMapper's Mapper class is sealed. Your implementation
can take IConfigurationProvider in its constructor to use the configuration
built from your profiles.
container.AddAutoMapper(cfg =>
{
cfg.Using<MyCustomMapper>();
cfg.WithMapperAssemblyMarkerTypes(typeof(UserProfile));
});
Unit Testing with Mock IMapper
Perfect for unit tests using Moq or similar frameworks.
Using(Func<IMapper>) calls the factory once during registration and uses the
returned mapper instead of constructing AutoMapper's configuration. You do not need
to scan profiles for a mock, and the library does not register IConfigurationProvider.
using AutoMapper;
using Moq;
var testMapper = new Mock<IMapper>();
testMapper.Setup(m => m.Map<UserDto>(It.IsAny<UserEntity>()))
.Returns(new UserDto(1, "Test User"));
container.AddAutoMapper(cfg => cfg.Using(() => testMapper.Object));
Setting the AutoMapper License Key
AutoMapper 16.3 reads AUTOMAPPER_LICENSE_KEY from the environment, falling back
to LUCKYPENNY_LICENSE_KEY. If your application gets the key from its own
configuration or secret store, pass it to WithLicenseKey instead. An explicit
key takes precedence. Do not hard-code the key in source.
container.AddAutoMapper(cfg =>
{
cfg.WithLicenseKey(licenseKey);
cfg.WithMapperAssemblyMarkerTypes(typeof(UserProfile));
});
Common Patterns
Using IMapper.Map
Inject IMapper into your services to perform runtime mapping:
public class EmployeesController
{
private readonly IMapper _mapper;
private readonly IEmployeeRepository _repository;
public EmployeesController(IMapper mapper, IEmployeeRepository repository)
{
_mapper = mapper;
_repository = repository;
}
public EmployeeDto GetEmployee(int id)
{
var employee = _repository.GetById(id);
return _mapper.Map<EmployeeDto>(employee);
}
public IEnumerable<EmployeeDto> GetAllEmployees()
{
var employees = _repository.GetAll();
return _mapper.Map<IEnumerable<EmployeeDto>>(employees);
}
}
Using ProjectTo for Entity Framework / LINQ
Use ProjectTo to project directly to DTOs. Define CreateProjection<Order, OrderDto>()
in your profile for a query-only mapping. Apply entity filters and sorting before
projecting. Use Map after materializing the query if the mapping requires a
dependency-injected resolver or other logic the query provider cannot translate.
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.EntityFrameworkCore;
public class OrderService
{
private readonly DbContext _dbContext;
private readonly IConfigurationProvider _configurationProvider;
public OrderService(DbContext dbContext, IConfigurationProvider configurationProvider)
{
_dbContext = dbContext;
_configurationProvider = configurationProvider;
}
// Option 1: Using IConfigurationProvider directly (recommended)
public async Task<List<OrderDto>> GetOrdersAsync()
{
return await _dbContext.Set<Order>()
.ProjectTo<OrderDto>(_configurationProvider)
.ToListAsync();
}
}
Or inject IMapper instead:
using AutoMapper;
using Microsoft.EntityFrameworkCore;
public class OrderService
{
private readonly DbContext _dbContext;
private readonly IMapper _mapper;
public OrderService(DbContext dbContext, IMapper mapper)
{
_dbContext = dbContext;
_mapper = mapper;
}
// Option 2: Using IMapper.ProjectTo
public async Task<List<OrderDto>> GetOrdersAsync()
{
return await _mapper.ProjectTo<OrderDto>(_dbContext.Set<Order>())
.ToListAsync();
}
}
API Reference
AddAutoMapper Extension Methods
| Method | Description |
|---|---|
AddAutoMapper(params Type[]) |
Register AutoMapper by scanning assemblies containing the specified types |
AddAutoMapper(params Assembly[]) |
Register AutoMapper by scanning the specified assemblies |
AddAutoMapper(IEnumerable<Assembly>) |
Register AutoMapper by scanning the specified assemblies |
AddAutoMapper(IEnumerable<Type>) |
Register AutoMapper by scanning assemblies containing the specified types |
AddAutoMapper(Action<AutoMapperSimpleInjectorConfiguration>) |
Register AutoMapper with custom configuration |
Configuration Methods
| Method | Description |
|---|---|
WithMapperAssemblyMarkerTypes(params Type[]) |
Specify types to mark assemblies for scanning (eagerly materialized, throws on null) |
WithMapperAssemblyMarkerTypes(IEnumerable<Type>) |
Specify a sequence of types to mark assemblies for scanning |
WithAssembliesToScan(IEnumerable<Assembly>) |
Specify assemblies to scan directly (defensively copied, throws on null) |
Using<TMapper>() |
Use a custom IMapper implementation |
Using(Func<IMapper>) |
Create a replacement IMapper once (useful for testing; skips IConfigurationProvider registration) |
AsSingleton() |
Register IMapper as Singleton (default) |
AsScoped() |
Register IMapper as Scoped |
AsTransient() |
Register IMapper as Transient |
WithMapperConfigurationExpressionAction(...) |
Add custom mapper configuration |
WithLicenseKey(string) |
Set an explicit AutoMapper license key (rejects null; ignores an empty key) |
Requirements
- .NET 10.0 or 11.0 (.NET 8 and 9 are no longer targeted)
- AutoMapper 16.3.0 or later, below 17.0.0
- SimpleInjector 5.6.0 or later, below 6.0.0
Running Tests Locally
Install the .NET 11 SDK to build the solution and the .NET 10 runtime to run the
net10.0 tests. Run the following from the repository root. The global.json file
selects Microsoft.Testing.Platform, and the command runs the tests for both target
frameworks.
dotnet test --configuration Release
The test suite checks that AUTOMAPPER_LICENSE_KEY is set. In CI the value comes
from the AUTOMAPPER_LICENSE_KEY GitHub secret (see .github/workflows/ci.yml).
To supply it locally, copy the template and fill in your key:
cp .env.example .env
AUTOMAPPER_LICENSE_KEY=your-license-key
.env is git ignored, so the key never lands in the repository. A module initializer in the test
project (TestEnvironment) uses dotenv.net to probe
upwards from the test output directory for the nearest .env and exports every KEY=VALUE entry
into the test process before the first MapperConfiguration is built. Variables that are already
set in the environment are never overwritten, so CI values always win over the file.
This works the same for dotnet test and for the test runners in Visual Studio, Rider, and VS Code.
If you prefer not to keep a file in the working tree, set a user-level environment variable instead
(setx AUTOMAPPER_LICENSE_KEY "your-license-key" on Windows) and restart your IDE or shell.
NuGet Releases
The CI workflow publishes packages to NuGet.org only after
the build succeeds for a lightweight version tag such as v16.3.0. Annotated tags
do not trigger package publishing.
Before releasing, configure NuGet Trusted Publishing
for this repository and set the NUGET_USER GitHub Actions secret to the NuGet.org
username, not the email address. The publish job uses a short-lived token instead
of a stored NuGet API key.
Credits
Special thanks to:
- Jimmy Bogard for creating AutoMapper
- Steven van Deursen for creating SimpleInjector
This library is based on AutoMapper.Extensions.Microsoft.DependencyInjection and adapted to work seamlessly with SimpleInjector.
License
Found this helpful? Give it a ⭐ on GitHub!
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | 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. |
-
net10.0
- AutoMapper (>= 16.3.0 && < 17.0.0)
- SimpleInjector (>= 5.6.0 && < 6.0.0)
-
net11.0
- AutoMapper (>= 16.3.0 && < 17.0.0)
- SimpleInjector (>= 5.6.0 && < 6.0.0)
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 |
|---|---|---|
| 15.0.0 | 103 | 11/26/2026 |
| 14.0.0 | 179 | 8/2/2026 |
| 13.1.0 | 205 | 4/4/2026 |
| 13.0.0 | 499 | 11/11/2025 |
| 12.0.0 | 318 | 10/26/2025 |
| 11.0.0 | 712 | 2/15/2025 |
| 10.0.0 | 362 | 11/13/2024 |
| 9.2.0 | 496 | 8/18/2024 |
| 9.1.0 | 342 | 5/27/2024 |
| 8.0.1 | 641 | 1/27/2024 |
| 8.0.0 | 691 | 11/29/2023 |
| 7.0.1 | 1,316 | 1/22/2023 |
| 7.0.0 | 1,067 | 11/13/2022 |
| 6.0.0 | 1,125 | 10/17/2022 |
| 5.1.0 | 1,126 | 7/24/2022 |
| 5.0.1 | 1,234 | 2/8/2022 |
| 5.0.0 | 1,017 | 1/6/2022 |
| 4.2.2 | 1,453 | 7/24/2021 |
| 4.2.1 | 1,045 | 6/27/2021 |
| 4.2.0 | 1,311 | 3/7/2021 |
- .NET 11 release