Automapper asp.net核心控制器-映射器未初始化错误

时间:2019-03-22 12:40:53

标签: c# automapper

我一直在查看本文档https://automapper.readthedocs.io/en/stable/Getting-started.html,以尝试配置自动映射器来消除一些手动属性映射的麻烦。

我遇到以下错误:

消息:System.InvalidOperationException:映射器未初始化。用适当的配置调用初始化。如果您尝试通过容器或其他方式使用mapper实例,请确保没有对静态Mapper.Map方法的任何调用,并且如果您使用的是ProjectTo或UseAsDataSource扩展方法,请确保传递适当的IConfigurationProvider实例。

该位-“未初始化映射器。使用适当的配置调用初始化”-之所以引起关注,是因为我觉得我已经在startup.cs文件中做到了。

我有以下控制器操作:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Index(NewCreditCardApplicationDetails applicationDetails)
    {
        if (!ModelState.IsValid)
        {
            return View(applicationDetails);
        }

        CreditCardApplication creditCardApplication = Mapper.Map<CreditCardApplication>(applicationDetails);

        //var creditCardApplication = new CreditCardApplication
        //{
        //    FirstName = applicationDetails.FirstName,
        //    LastName = applicationDetails.LastName,
        //    Age = applicationDetails.Age.Value,
        //    GrossAnnualIncome = applicationDetails.GrossAnnualIncome.Value,
        //    FrequentFlyerNumber = applicationDetails.FrequentFlyerNumber
        //};

        await _applicationRepository.AddAsync(creditCardApplication);

        return View("ApplicationComplete", creditCardApplication);
    }

带注释的行表示确实有效,但是我想删除。

我的asp.net核心网络应用程序中startup.cs文件中的configure方法如下:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, AppDbContext dbContext)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            dbContext.Database.EnsureCreated();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();

        Mapper.Initialize(cfg =>
        {
            cfg.CreateMap<NewCreditCardApplicationDetails, CreditCardApplication>();
        });

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

NewCreditCardApplicationDetails.cs看起来像这样:

public class NewCreditCardApplicationDetails
{
    [Display(Name = "First Name")]
    [Required(ErrorMessage = "Please provide a first name")]
    public string FirstName { get; set; }

    [Display(Name = "Last Name")]
    [Required(ErrorMessage = "Please provide a last name")]
    public string LastName{ get; set; }

    [Display(Name = "Age (in years)")]
    [Required(ErrorMessage = "Please provide an age in years")]
    [Range(18,int.MaxValue, ErrorMessage = "You must be at least 18 years old")]
    public int? Age { get; set; }

    [Display(Name = "Gross Income")]
    [Required(ErrorMessage = "Please provide your gross income")]        
    public decimal? GrossAnnualIncome { get; set; }
    public string FrequentFlyerNumber { get; set; }
}

CreditCardApplication.cs看起来像这样:

public class CreditCardApplication
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
    public decimal GrossAnnualIncome { get; set; }
    public string FrequentFlyerNumber { get; set; }
}

任何人都可以看到问题所在吗?

谢谢。

1 个答案:

答案 0 :(得分:0)

签出此项:https://medium.com/ps-its-huuti/how-to-get-started-with-automapper-and-asp-net-core-2-ecac60ef523f

您应该注入映射器以使用它,而不要使用静态映射器。