c# - ASP.NET 核心 2.2 : Unable to resolve service for type 'AutoMapper.IMapper'

标签 c# api asp.net-core .net-core asp.net-core-mvc

ASP.NET Core(版本:2.2.102)

我正在构建一个 API 来返回 Portos 和 Especies,但是每当我访问/api/portos(在 Controller 中定义)时,我都会收到此错误:

InvalidOperationException: Unable to resolve service for type 'AutoMapper.IMapper' while attempting to activate 'fish.Controllers.PortosController'.

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

我不确定我做错了什么,所以感谢任何帮助。


模型


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

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 >资源

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; }
    }
}

更多相关代码


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

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; }
    }
}

最佳答案

您将必须使用如下所示的 automapper 包:

Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection

如果您还没有 Automapper nuget 包,这也会依次安装它。

然后,在 startup.cs 的 ConfigureServices 方法中,您必须添加一个调用,如下所示。

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

引用this blog for more details.

编辑:

有很好的描述from this thread.

你需要在startup.cs中添加如下代码。

您错过了在 DI 中添加 IMapper。请引用以下代码添加单例调用。

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();

}

编辑:06-07-21: 请参阅此博客文章,其中解释了如何使用 AutoMapper with latest .NET

关于c# - ASP.NET 核心 2.2 : Unable to resolve service for type 'AutoMapper.IMapper' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54239669/

相关文章:

c# - 使用 Ninject 查找实现通用接口(interface)的类

C#:不显示 Excel 插件功能区选项卡

asp.net-core - ForbidAsync 与 ChallengeAsync 为什么以及何时使用它们

asp.net-core - 连接到本地 Identity Server 4 的新 Blazor 项目

C# : How do I get the actual item clicked from SelectedIndexChanged for a ListView control?

c# - 在 C# 中将 XML 反序列化为对象

python - 编程从 Bloomberg 终端获取数据

javascript - 来自 Rails Controller 的 JSON 自定义格式

python - 如何爬取具有多个页面的 API

c# - 无法加载类型 ServiceCollectionExtensions