我試圖讓AutoMapper在我們的應用程序中工作。我們正在使用版本6.0.2。我已經按照實例過多而這裏就是我這麼遠:設置後自動映射器爲NULL
的ViewModels \ AutoMapperProfileConfiguration.cs
using AutoMapper;
using Models;
using ViewModels;
namespace App
{
public class AutoMapperProfileConfiguration : Profile
{
public AutoMapperProfileConfiguration()
{
CreateMap<Models.Source, ViewModels.Destination>();
}
}
}
Startup.cs
public class Startup
{
private MapperConfiguration _mapperConfiguration { get; set; }
public Startup(IHostingEnvironment env)
{
...
_mapperConfiguration = new MapperConfiguration(cfg =>
{
cfg.AddProfile(new AutoMapperProfileConfiguration());
});
...
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IMapper>(sp => _mapperConfiguration.CreateMapper());
...
}
}
控制器\ BaseController.cs
public class BaseController : Controller
{
protected readonly IMapper _mapper;
public BaseController(..., IMapper mapper)
{
...
_mapper = mapper;
}
}
個
控制器\ HomeController.cs
public class HomeController : BaseController
{
public HomeController(..., IMapper mapper) :
base(..., mapper)
{
}
public IActionResult Action()
{
Model.Source x = ...;
ViewModel.Destination y = _mapper.Map<ViewModel.Destination>(x);
return View(y);
}
}
的問題是,它似乎CreateMapper
工作不正常。這是我得到的服務列表services.AddSingleton
後:
而且每當BaseController時,這裏是mapper
樣子:
下面是發生在什麼它到達HomeController:
System.NullReferenceException occurred
HResult=0x80004003
Message=Object reference not set to an instance of an object.
是什麼原因造成:
而這個錯誤當它試圖映射源到目的地發生?這與我的建立有關嗎?我的假設是,這一切都源自services
具有看起來像映射器的NULL實例。但我不知道是什麼原因造成的。
試試'services.AddSingleton(_mapperConfiguration。CreateMapper());' –
這裏的區別在於你可以隱式捕獲'_mapperConfiguration'閉包。因此,通過使用工廠,您可以推遲對「CreateMapper」的調用,直到實例被銷燬...可能 - 但是,按照我描述的方式,您實際上在創建時放棄了映射器的實例它(與所有的配置等) –
只是爲了好奇,你爲什麼試圖注入IMapper接口到服務?爲什麼不用簡單的方法去調用靜態方法'Mapper.Map(x)' –