asp.net-mvc 试图将 AutoMapper 添加到 Asp.net Core 2?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50411188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-07 23:38:24  来源:igfitidea点击:

Trying to add AutoMapper to Asp.net Core 2?

asp.net-mvcasp.net-coreautomapperasp.net-core-2.0

提问by topcool

I worked on a asp.net core 1.1 project a while ago and use in projetc AutoMapper.

不久前我参与了一个 asp.net core 1.1 项目,并在 projetc AutoMapper 中使用。

in asp.net core 1.1, I add services.AddAutoMapper()in startup file :

在asp.net core 1.1中,我添加services.AddAutoMapper()了启动文件:

StartUp file in asp.net core 1.1:

asp.net core 1.1 中的启动文件:

    public void ConfigureServices(IServiceCollection services)
    {
        //Some Code

        services.AddMvc();
        services.AddAutoMapper();
    }

And I use AutoMapper in Controller easily.

我很容易在 Controller 中使用 AutoMapper。

Controller :

控制器 :

 public async Task<IActionResult> AddEditBook(AddEditBookViewModel model)
 {
    Book bookmodel = AutoMapper.Mapper.Map<AddEditBookViewModel, Book>(model);
    context.books.Add(bookmodel);
    context.SaveChanges();
 }

And everything was fine. But I'm currently working on a Asp.net Core 2 project and I get the error with services.AddAutoMapper()in sturtap file.

一切都很好。但是我目前正在处理一个 Asp.net Core 2 项目,并且services.AddAutoMapper()在 sturtap 文件中出现错误。

Error CS0121 The call is ambiguous between the following methods or properties: 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[])' and 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Type[])'

错误 CS0121 调用在以下方法或属性之间不明确:“ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[])”和“ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Type[])”

What is the reason for this error? Also, services.AddAutoMapperin asp.net core 2 has some parameters. what should I send to this parameter?

这个错误的原因是什么?此外,services.AddAutoMapper在 asp.net core 2 中有一些参数。我应该向这个参数发送什么?

采纳答案by Tseng

You likely updated your ASP.NET Core dependencies, but still using outdated AutoMapper.Extensions.Microsoft.DependencyInjectionpackage.

您可能更新了 ASP.NET Core 依赖项,但仍在使用过时的AutoMapper.Extensions.Microsoft.DependencyInjection包。

For ASP.NET Core you need at least Version 3.0.1from https://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/3.0.1

对于 ASP.NET Core,您至少需要3.0.1来自 https://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/3.0.1 的版本

Which references AutoMapper 6.1.1 or higher.

其中引用 AutoMapper 6.1.1 或更高版本。

AutoMapper (>= 6.1.1)

Microsoft.Extensions.DependencyInjection.Abstractions (>= 2.0.0)

Microsoft.Extensions.DependencyModel (>= 2.0.0)

AutoMapper (>= 6.1.1)

Microsoft.Extensions.DependencyInjection.Abstractions (>= 2.0.0)

Microsoft.Extensions.DependencyModel (>= 2.0.0)

The older packages depend on Microsoft.Extensions.DependencyInjection.Abstractions1.1.0and can't be used with ASP.NET Core since there have been breaking changes between Microsoft.Extensions.DependencyInjection.Abstractions1.1.0 and 2.0

Microsoft.Extensions.DependencyInjection.Abstractions1.1.0由于Microsoft.Extensions.DependencyInjection.Abstractions1.1.0 和 2.0之间发生了重大更改,因此较旧的软件包依赖于ASP.NET Core 并且不能与 ASP.NET Core 一起使用

回答by dev-siberia

If you are using AspNet Core 2.2 and AutoMapper.Extensions.Microsoft.DependencyInjection v6.1 You need to use in Startup file

如果您使用的是 AspNet Core 2.2 和 AutoMapper.Extensions.Microsoft.DependencyInjection v6.1 您需要在启动文件中使用

services.AddAutoMapper(typeof(Startup));

回答by Mohammad Dayyan

In new version (6.1) of AutoMapper.Extensions.Microsoft.DependencyInjectionnuget package you should use it as follows:

AutoMapper.Extensions.Microsoft.DependencyInjectionnuget 包的新版本 (6.1) 中,您应该按如下方式使用它:

services.AddAutoMapper(Type assemblyTypeToSearch);
// OR
services.AddAutoMapper(params Type[] assemblyTypesToSearch);

回答by Yasen Raykov

None of these worked for me, I have a .NET Core 2.2 project and the complete code for configuring the mapper looks like this(part of ConfigureService() method):

这些都不适合我,我有一个 .NET Core 2.2 项目,配置映射器的完整代码如下所示(ConfigureService() 方法的一部分):

    // Auto Mapper Configurations
    var mappingConfig = new MapperConfiguration(mc =>
    {
        mc.AddProfile(new SimpleMappings());
    });

    IMapper mapper = mappingConfig.CreateMapper();
    services.AddSingleton(mapper);

Then I have my Mappings class which I've placed in the BL project:

然后我有我放在 BL 项目中的 Mappings 类:

public class SimpleMappings : Profile
    {
        public SimpleMappings()
        {
            CreateMap<DwUser, DwUserDto>();
            CreateMap<DwOrganization, DwOrganizationDto>();
        }
    }

And finally the usage of the mapper looks like this:

最后,映射器的用法如下所示:

public class DwUserService : IDwUserService
    {
        private readonly IDwUserRepository _dwUserRepository;
        private readonly IMapper _mapper;

        public DwUserService(IDwUserRepository dwUserRepository, IMapper mapper)
        {
            _dwUserRepository = dwUserRepository;
            _mapper = mapper;
        }

        public async Task<DwUserDto> GetByUsernameAndOrgAsync(string username, string org)
        {
            var dwUser = await _dwUserRepository.GetByUsernameAndOrgAsync(username, org).ConfigureAwait(false);
            var dwUserDto = _mapper.Map<DwUserDto>(dwUser);

            return dwUserDto;
        }
}

Here is a similar link on the same topic: How to setup Automapper in ASP.NET Core

这是关于同一主题的类似链接: How to setup Automapper in ASP.NET Core

回答by CodeRed

I solved this by creating a class that inherits AutoMapper.Profile

我通过创建一个继承的类解决了这个问题 AutoMapper.Profile

    public class model_to_resource_profile : Profile
    {
        public model_to_resource_profile()
        {
            CreateMap<your_model_class, your_model_resource_class>();
        }
    }

And adding this line in the Startup.cs:

并在以下内容中添加这一行Startup.cs

services.AddAutoMapper(typeof(model_to_resource_profile ));

回答by AminGolmahalle

If you are using AspNet Core 2.2.Try changing your code from:

如果您使用的是 AspNet Core 2.2。请尝试从以下位置更改您的代码:

services.AddAutoMapper();

To:

到:

services.AddAutoMapper(typeof(Startup));

It worked for me!

它对我有用!

回答by Manzur Alahi

try this, works with 2.1 and up, i have not used any previous version so can't tell.

试试这个,适用于 2.1 及更高版本,我没有使用过任何以前的版本所以不知道。

services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

回答by R M Shahidul Islam Shahed

Install package:

安装包:

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 7.0.0

Nuget:
https://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/

Nuget:https ://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/

In Startup Class:

在创业班:

services.AddAutoMapper(typeof(Startup));

回答by Askar Rayapov

The official docs: https://automapper.readthedocs.io/en/latest/Dependency-injection.html#asp-net-core

官方文档:https: //automapper.readthedocs.io/en/latest/Dependency-injection.html#asp-net-core

You define the configuration using profiles. And then you let AutoMapper know in what assemblies are those profiles defined by calling the IServiceCollection extension method AddAutoMapper at startup:

您可以使用配置文件定义配置。然后让 AutoMapper 知道在启动时调用 IServiceCollection 扩展方法 AddAutoMapper 定义的那些配置文件在哪些程序集中:

services.AddAutoMapper(profileAssembly1, profileAssembly2 /*, ...*/);

or marker types:

或标记类型:

services.AddAutoMapper(typeof(ProfileTypeFromAssembly1), typeof(ProfileTypeFromAssembly2) /*, ...*/);

回答by ChristianProgrammer

Dec 6th 2019 Based upon initial attempt in a pluralsight course Building an API with ASP.NET Core by Shawn Wildermuth. As I got the error "...ambiguous 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[])..."

2019 年 12 月 6 日基于 Shawn Wildermuth 所著的使用 ASP.NET Core 构建 API 的多元视觉课程的初步尝试。当我收到错误“...模糊的 'ServiceCollectionExtensions.AddAutoMapper(IServiceCollection, params Assembly[])...”

I started researching proper syntax to implement AddAutoMapper in Core 2.2. My NuGet reference is version 7.0.0 After the tutorial had me create the Profile class in my Data repository directory which additionally referenced my model nir weiner & dev-siberia's answers above led me to trying to reference the profile class in the Startup.ConfigureServices() by name:

我开始研究在 Core 2.2 中实现 AddAutoMapper 的正确语法。我的 NuGet 参考版本是 7.0.0 在本教程让我在我的数据存储库目录中创建 Profile 类之后,该类还引用了我的模型 nir weiner 和 dev-siberia 上面的答案,这导致我尝试在 Startup.ConfigureServices( ) 按名字:

services.AddAutoMapper(typeof(CampProfile));

the content of the profile class is just a (no pun intended) old school map of the data class and the model in its constructor

profile 类的内容只是数据类及其构造函数中模型的(无双关语)老派地图

this.CreateMap<Camp, CampModel>();  

This addressed the poor lack of documentation for this current version.

这解决了当前版本缺乏文档的问题。

Respectfully,

尊敬,

ChristianProgrammer

基督徒程序员