我试图让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)' –