https://github.com/carl-hugo/automapperdependencyinjectionsample
Code sample that shows how to use Dependency Injection using AutoMapper and ASP.NET Core.
https://github.com/carl-hugo/automapperdependencyinjectionsample
Last synced: 3 months ago
JSON representation
Code sample that shows how to use Dependency Injection using AutoMapper and ASP.NET Core.
- Host: GitHub
- URL: https://github.com/carl-hugo/automapperdependencyinjectionsample
- Owner: Carl-Hugo
- License: mit
- Created: 2017-12-31T20:16:33.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2017-12-31T21:06:45.000Z (over 7 years ago)
- Last Synced: 2025-01-06T09:29:25.234Z (5 months ago)
- Language: C#
- Size: 10.7 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# AutoMapperDependencyInjectionSample
This code sample shows how to use Dependency Injection using AutoMapper and ASP.NET Core.
The code also uses the `AutoMapper.Extensions.Microsoft.DependencyInjection` package ([source code on GitHub](https://github.com/AutoMapper/AutoMapper.Extensions.Microsoft.DependencyInjection)).## Some facts
1. Dependencies can't be injected into `Profile` classes.
2. Dependencies can be injected into smaller mapping logic block like `IMappingAction` implementations.## How it works
To use Dependency Injection, I created `MyAfterMapAction` class that is connected to `SomeProfile` as follow:``` csharp
namespace AutoMapperDependencyInjectionSample
{
public class SomeProfile : Profile
{
public SomeProfile()
{
CreateMap()
.AfterMap();
}
}
public class MyAfterMapAction : IMappingAction
{
private readonly IHttpContextAccessor _httpContextAccessor;public MyAfterMapAction(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));
}public void Process(SomeModel source, SomeOtherModel destination)
{
destination.TraceIdentifier = _httpContextAccessor.HttpContext.TraceIdentifier;
}
}
}
```This is possible because of `AutoMapper.Extensions.Microsoft.DependencyInjection`.
In `Startup.ConfigureServices`, the following line of code do all the job for us and scans my assembly for implementations of `IValueResolver<,,>`, `IMemberValueResolver<,,,>`, `ITypeConverter<,>` and `IMappingAction<,>`.
``` csharp
services.AddAutoMapper(typeof(Startup).Assembly);
```And voila!