I'm trying to get AutoMapper working in our application. We're using version 6.0.2. I've followed a plethora of examples and here's what I've got so far:
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());
...
}
}
Controllers\BaseController.cs
public class BaseController : Controller
{
protected readonly IMapper _mapper;
public BaseController(..., IMapper mapper)
{
...
_mapper = mapper;
}
}
Controllers\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);
}
}
The problem is that it seems that CreateMapper
is not working properly. Here's what I get in the list of services after services.AddSingleton
:
And whenever the BaseController is used, here's what mapper
looks like:
And here's what happens when it gets to the HomeController:
And this error occurs when it tries to map the source to the destination:
System.NullReferenceException occurred
HResult=0x80004003
Message=Object reference not set to an instance of an object.
What is causing this? Is it related to my set up? My assumption is that it all stems from the services
having what looks like a NULL instance for the mapper. But I don't know what is causing this.
Since AutoMapperProfileConfiguration inherits Profile, all you need is to use AutoMapper middle-ware.
You could install it via this NuGet - AutoMapper.Extensions.Microsoft.DependencyInjection
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc();
services.AddAutoMapper();
}
}
Note: Remove automapper related code inside your Startup.cs. You don't need any of those.
Let AutoMapper
singletons do the work.
public Startup(IHostingEnvironment env)
{
Mapper.Initialize(c =>
{
c.AddProfile<AutoMapperProfileConfiguration>();
});
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton(s => Mapper.Instance);
}
Then the injected IMapper
should contain the profiles.
User contributions licensed under CC BY-SA 3.0