When I was using Automapper v6 (I'm using .net core), I had this command to validate configuration :
configuration.AssertConfigurationIsValid();
But now, after moving to the latest version, I don't have this since my config is exactly ( docs ):
private void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(AppSettingsMappingProfile)); //marker type
}
However, I still want to validate all mappings at startup .
The docs says that I need to do this :
var configuration = new MapperConfiguration(cfg =>
cfg.CreateMap<Source, Destination>());
configuration.AssertConfigurationIsValid();
But I don't have it since I'm using profiles with this command :
services.AddAutoMapper(typeof(AppSettingsMappingProfile));
Question :
How can I still make AutoMapper scan for validation at startup?
If you look at the source code for AddAutoMapper , you will see that it registers IConfigurationProvider
as singleton. This means you can safely have it in your Configure method and do the validation there:
public void Configure(IConfigurationProvider pr)
{
pr.AssertConfigurationIsValid();
}
Following these steps should work:
services.AddAutoMapper(typeof(...))
within ConfigureServices(...)
.IMapper mapper
as parameter to Configure(...)
methodmapper.ConfigurationProvider.AssertConfigurationIsValid();
within Configure(...)
Example (omitting namespace inclusion)
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(typeof(Startup));
}
public void Configure(IApplicationBuilder app, IMapper mapper)
{
mapper.ConfigurationProvider.AssertConfigurationIsValid();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.