在ASP.NET Core中使用AutoMapper的问题

时间:2018-09-02 05:48:38

标签: asp.net asp.net-core

我正在关注有关asp.net核心和angular的教程。当我在Startup类中添加Automapper时,它使dotnet cli崩溃,并且无法呈现页面。这就是我在Startup中使用自动映射器的方式:

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

以及在我的映射配置文件中

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

1 个答案:

答案 0 :(得分:1)

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


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


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

PS。但是我不能告诉您为什么此异常会导致整个应用程序崩溃