I'm relatively new at .NET, and I decided to tackle .NET Core instead of learning the "old ways". I found a detailed article about setting up AutoMapper for .NET Core here, but is there a more simple walkthrough for a newbie?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
about theutz answer , there is no need to specify the IMapper mapper parrameter at the controllers constructor.
you can use the Mapper as it is a static member at any place of the code.
services.AddAutoMapper(); didn't work for me. (I am using Asp.Net Core 2.0)
After configuring as below
initialize the mapper IMapper mapper = config.CreateMapper();
and add the mapper object to services as a singleton services.AddSingleton(mapper);
this way I am able to add a DI to controller
and I have used as below in my action methods
To add onto what Arve Systad mentioned for testing. If for whatever reason you're like me and want to maintain the inheritance structure provided in theutz solution, you can set up the MapperConfiguration like so:
I did this in NUnit.
I am using AutoMapper 6.1.1 and asp.net Core 1.1.2.
First of all, define Profile classes inherited by Profile Class of Automapper. I Created IProfile interface which is empty, the purpose is only to find the classes of this type.
Now create a separate class e.g Mappings
Now in MVC Core web Project in Startup.cs file, in the constructor, call Mapping class which will initialize all mappings at the time of application loading.
theutz' answer here is very good, I just want to add this:
If you let your mapping profile inherit from
MapperConfigurationExpression
instead ofProfile
, you can very simply add a test to verify your mapping setup, which is always handy:I want to extend @theutz's answers - namely this line :
There is a bug (probably) in AutoMapper.Extensions.Microsoft.DependencyInjection version 3.2.0. (I'm using .NET Core 2.0)
This is tackled in this GitHub issue. If your classes inheriting AutoMapper's Profile class exist outside of assembly where you Startup class is they will probably not be registered if your AutoMapper injection looks like this:
unless you explicitly specify which assemblies to search AutoMapper profiles for.
It can be done like this in your Startup.ConfigureServices:
where "assemblies" and "type_in_assemblies" point to the assembly where Profile classes in your application are specified. E.g:
I suppose (and I put emphasis on this word) that due to following implementaion of parameterless overaload (source code from GitHub) :
we rely on CLR having already JITed assembly containing AutoMapper profiles which might be or might not be true as they are only jitted when needed (more deatils in this StackOverflow question).