代码之家  ›  专栏  ›  技术社区  ›  Gonçalo Peres

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

  •  1
  • Gonçalo Peres  · 技术社区  · 5 年前

    ASP.NET核心(版本:2.2.102)

    我正在构建一个API以返回Portos和Species,但每当我访问/API/Portos(在控制器中定义)时,我都会遇到以下错误:

    InvalidOperationException:无法解析类型的服务 “鱼。控制器。端口控制器”。

    Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp,类型类型,类型要求者,布尔isDefaultParameterRequired)

    我不确定我做错了什么,所以非常感谢您的帮助。


    模型


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

    波尔图

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

    控制器


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

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

    特别资源

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

    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; }
        }
    }
    
    1 回复  |  直到 5 年前
        1
  •  28
  •   Manoj Choudhari    3 年前

    您必须使用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.

    您没有在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

        2
  •  2
  •   mspaic96    3 年前

    如果您使用的是.NET CORE 5。首先转到nuget软件包,查找并安装AutoMapper.Extensions.Microsoft.DependencyInjection enter image description here

    enter image description here 然后您应该在Startup类的ConfigureServices方法中添加Automapper

     services.AddAutoMapper(typeof(CommonMappingProfile));