简体   繁体   English

ASP.NET Core 2.2:无法解析“AutoMapper.IMapper”类型的服务

[英]ASP.NET Core 2.2: Unable to resolve service for type 'AutoMapper.IMapper'

ASP.NET Core (Version: 2.2.102) ASP.NET 核心(版本:2.2.102)

I am building an API to return Portos and Especies, but anytime that I access /api/portos (as defined in the controller), I get this error:我正在构建一个 API 来返回 Portos 和 Especies,但是任何时候我访问 /api/portos(在控制器中定义),我都会收到此错误:

InvalidOperationException: Unable to resolve service for type 'AutoMapper.IMapper' while attempting to activate 'fish.Controllers.PortosController'. InvalidOperationException:尝试激活“fish.Controllers.PortosController”时无法解析“AutoMapper.IMapper”类型的服务。

Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired) Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)

I am not sure what am I doing wrong, so any help is appreciated.我不确定我做错了什么,所以任何帮助表示赞赏。


Models楷模


Especie.cs Especie.cs

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace fish.Models
{
    [Table("Especies")]
    public class Especie
    {
        public int Id { get; set; }
        [Required]
        [StringLength(255)]
        public string Nome { get; set; }

        public Porto Porto { get; set; }
        public int PortoId { get; set; }
    }
}

Porto.cs波尔图

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;

namespace fish.Models
{
    public class Porto
    {
        public int Id { get; set; }
        [Required]
        [StringLength(255)]
        public string Nome { get; set; }
        public ICollection<Especie> Models { get; set; }

        public Porto()
        {
            Models = new Collection<Especie>();
        }
    }
}

Controller控制器


PortoController.cs端口控制器.cs

using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using fish.Controllers.Resources;
using fish.Models;
using fish.Persistence;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace fish.Controllers
{
    public class PortosController : Controller
    {
        private readonly FishDbContext context;
        private readonly IMapper mapper;
        public PortosController(FishDbContext context, IMapper mapper)
        {
            this.mapper = mapper;
            this.context = context;
        }


        [HttpGet("/api/portos")]
        public async Task<IEnumerable<PortoResource>> GetPortos()
        {
            var portos = await context.Portos.Include(m => m.Models).ToListAsync();

            return mapper.Map<List<Porto>, List<PortoResource>>(portos);
        }

    }
}

Controller>Resources控制器>资源

PortoResources.cs波尔图资源

using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace fish.Controllers.Resources
{
    public class PortoResource
    {
        public int Id { get; set; }
        public string Nome { get; set; }
        public ICollection<EspecieResource> Models { get; set; }

        public PortoResource()
        {
            Models = new Collection<EspecieResource>();
        }
    }
}

EspecieResource.cs特殊资源文件

namespace fish.Controllers.Resources
{
    public class EspecieResource
    {
        public int Id { get; set; }
        public string Nome { get; set; }
    }
}

More Relevant Code更多相关代码


Stratup.cs Stratup.cs

public void ConfigureServices(IServiceCollection services)
{
        services.AddAutoMapper();

        services.AddDbContext<FishDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

        // In production, the Angular files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/dist";
        });
}

MappingProfile.cs映射配置文件

using AutoMapper;
using fish.Controllers.Resources;
using fish.Models;

namespace fish.Mapping
{
    public class MappingProfile : Profile
    {
        public MappingProfile()
        {
            CreateMap<Porto, PortoResource>();
            CreateMap<Especie, EspecieResource>();
        }
    }
}

FishDbContext.cs FishDbContext.cs

using fish.Models;
using Microsoft.EntityFrameworkCore;

namespace fish.Persistence
{
    public class FishDbContext : DbContext
    {
        public FishDbContext(DbContextOptions<FishDbContext> options) : base(options)
        {

        }

        public DbSet<Porto> Portos { get; set; }
    }
}

You will have to use automapper package as shown below: 您将必须使用automapper包,如下所示:

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

This will also in turn install the Automapper nuget package if you don't have it already. 如果您还没有安装Automapper nuget包,它也会安装。

Then, inside your ConfigureServices method of your startup.cs, you will have to add a call to it as shown below. 然后,在startup.cs的ConfigureServices方法中,您必须添加一个调用,如下所示。

public void ConfigureServices(IServiceCollection services)
{
    services.AddAutoMapper();
}

Refer this blog for more details. 有关详细信息,请参阅此博客。

EDIT: 编辑:

There is very nice description from this thread. 这个帖子有很好的描述

You need to add code like below in startup.cs. 您需要在startup.cs中添加如下代码。

You have missed to add IMapper in DI. 您错过了在DI中添加IMapper。 Please refer add Singleton call from below code. 请参考以下代码添加Singleton调用。

public void ConfigureServices(IServiceCollection services) {
    // .... Ignore code before this

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

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

    services.AddMvc();

}

In case you are using .NET CORE 5. First go to nuget packages, find and install AutoMapper.Extensions.Microsoft.DependencyInjection如果您使用的是 .NET CORE 5。首先转到 nuget 包,找到并安装 AutoMapper.Extensions.Microsoft.DependencyInjection 在此处输入图片说明

Then you should extend Profile from Automapper and write mappings for your classes.然后你应该从 Automapper 扩展 Profile 并为你的类编写映射。 Something like this below像下面这样的东西在此处输入图片说明 Then you should add Automapper in ConfigureServices method in Startup class.This typeof(CommonMappingProfile) can be omitted if your nuget package for AutoMapper is in the same project as your mapping profile class.然后你应该在 Startup 类的 ConfigureServices 方法中添加 Automapper。如果 AutoMapper 的 nuget 包与映射配置文件类在同一个项目中,则可以省略此 typeof(CommonMappingProfile)。

 services.AddAutoMapper(typeof(CommonMappingProfile));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法使用 AutoMapper 4.2 和 Autofac 解析 AutoMapper.IMapper - Cannot resolve AutoMapper.IMapper using AutoMapper 4.2 with Autofac Asp.Net Core 2.2-无法解析类型为“…SignInHelper`1 […ApplicationUser]”的服务 - Asp.Net Core 2.2 - Unable to resolve service for type '…SignInHelper`1[…ApplicationUser]' ASP.Net Core 2无法解析类型服务 - ASP.Net Core 2 Unable to resolve service for type ASP.NET 核心依赖注入错误 - 尝试激活“服务”时无法解析“存储库”类型的服务 - ASP.NET Core Dependency Injection error - Unable to resolve service for type “Repository” while attempting to activate “Service” ASP.NET Core API,Mediatr send方法引发无法解析类型服务的异常 - ASP.NET Core API, Mediatr send method raises exception unable to resolve service for type ASP.NET Core 2 无法解析 Microsoft EntityFrameworkCore DbContext 类型的服务 - ASP.NET Core 2 Unable to resolve service for type Microsoft EntityFrameworkCore DbContext ASP.NET Core 错误:尝试激活时无法解析类型服务 - ASP.NET Core error: Unable to resolve service for type while attempting to activate 依赖注入错误:尝试激活时无法解析类型的服务,而 class 已注册 - Dependency Injection error: Unable to resolve service for type while attempting to activate, while class is registered ASP.NET 核心 - System.InvalidOperationException:尝试激活时无法解析服务类型 - ASP.NET Core - System.InvalidOperationException: Unable to resolve service for type while attempting to activate ASP.Net Core - 尝试激活 *Controller 时无法解析 *Context 类型的服务 - ASP.Net Core - Unable to resolve service for type *Context while attempting to activate *Controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM