【问题标题】:Automapper asp.net core Controller - Mapper Not Initialized ErrorAutomapper asp.net 核心控制器 - 映射器未初始化错误
【发布时间】:2019-03-22 12:40:53
【问题描述】:

我一直在看这个文档https://automapper.readthedocs.io/en/stable/Getting-started.html 尝试配置 automapper 以消除一些手动属性映射的痛苦。

我遇到了以下错误:

消息:System.InvalidOperationException:映射器未初始化。使用适当的配置调用初始化。如果您尝试通过容器或其他方式使用映射器实例,请确保您没有对静态 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 文件中的配置方法如下所示:

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

谁能看看是什么问题?

谢谢。

【问题讨论】:

标签: c# automapper


【解决方案1】:

查看:https://medium.com/ps-its-huuti/how-to-get-started-with-automapper-and-asp-net-core-2-ecac60ef523f

你应该注入映射器来使用它,不要使用静态的。

【讨论】:

  • 那是一篇好文章 - 谢谢。我现在有另一个问题,虽然这可能需要另一个问题:我得到了 UserViewModel viewModel = _mapper.Map(user);在我的应用程序中看起来相当于 CreditCardApplication cca = _mapper.Map(applicationDetails);其中源和 cca 中的 applicationDetails 是目标,但我在这里遇到错误 - 尝试解决这些错误最终会导致这一行: CreditCardApplication cca = _mapper.Map(applicationDetails);但随后 cca 为空。
  • @dstewart101 您是否创建了一个继承自的类: Profile 并在您“注册”这两种类型的构造函数中调用 CreateMap?请记住,当道具是公开的并且具有相同的名称时,映射器会映射道具
  • 嗨 daniel - 感谢您的回复......在阅读了提供的文章后,我遇到了另一个问题并在此处发布了问题:stackoverflow.com/questions/55302237/…。仍然无法让它工作:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 2018-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多