在asp.net核心中使用AutoMapper的问题

问题描述 投票:0回答:1

我正在关注asp.net core和angular的教程。当我在我的Startup类中添加Automapper时,它崩溃了dotnet cli并且无法呈现页面。这就是我在Startup中使用Automapper的方法:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using aspcoreangular.persistence;
using AutoMapper;

namespace aspcoreangular
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddAutoMapper();
            services.AddDbContext<VegaDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("Default")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

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

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }
}

这就是我在控制器中使用它的方式。但它没有达到这一点

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using aspcoreangular.models;
using aspcoreangular.persistence;
using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace aspcoreangular.Controllers
{
    public class MakesController : Controller
    {
        private readonly VegaDbContext context;
        private readonly IMapper mapper;

        protected MakesController(VegaDbContext context, IMapper mapper)
        {
            this.mapper = mapper;
            this.context = context;
        }

        [HttpGet("/api/makes")]
        public async Task<IEnumerable<Resources.MakeResource>> GetMakes()
        {
            var makes =  await context.Makes.Include(m => m.Models).ToListAsync();
            return mapper.Map<List<Make>, List<Resources.MakeResource>>(makes);
        }
    }
}

这是崩溃的形象:enter image description here你能帮我解决这个问题吗?谢谢。

这是我的MakeResouce课程

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using aspcoreangular.models;

namespace aspcoreangular.Controllers.Resources
{
    public class MakeResource
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public ICollection<ModelResource> Models { get; set; }

        public MakeResource()
        {
            Models = new Collection<ModelResource>();
        }
    }
}

并在我的mappingprofile中

using aspcoreangular.Controllers.Resources;
using aspcoreangular.models;
using AutoMapper;

namespace aspcoreangular.ClientApp.Mapping
{
    public class MappingProfile : Profile
    {
        protected MappingProfile()
        {
            CreateMap<Make, MakeResource>();
            CreateMap<Model, ModelResource>();
        }
    }
}
asp.net asp.net-core
1个回答
1
投票

当AutoMapper在映射自身之前将源对象映射到目标对象时,它必须创建目标对象的实例,然后Mapper可以使用反射映射属性。错误说明:没有为此对象定义无参数构造函数。


这意味着:AutoMapper请求System.Activator类为他创建目标对象的实例。但System.Activator失败是因为它无法在目标类中找到公共无参数构造函数(显然,System.Activator可以使用带参数的构造函数,但AutoMapper没有为构造函数提供任何参数)。这就是为什么Error消息的第三行来自Activator.CreateInstance方法。


因此,总而言之,您应该检查无参数构造函数的Resources.MakeResource类(作为目标)。

PS。但我无法告诉你为什么这个异常会崩溃整个应用程序

© www.soinside.com 2019 - 2024. All rights reserved.