问题
Error: No parameterless constructor for AutoMapperConfiguration
I am using the nuget package automapper DI
public class AutoMapperConfiguration : Profile
{
private readonly ICloudStorage _cloudStorage;
public AutoMapperConfiguration(ICloudStorage cloudStorage)
{
_cloudStorage = cloudStorage;
// Do mapping here
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICloudStorage, AzureStorage>();
services.AddAutoMapper(); // Errors here
}
How do I use the automapper DI with parameters?
回答1:
I don't think you are able to add DI parameters to Profile
s. Part of the logic behind this may be that these are only instantianted once, so services registered through AddTransient
would not behave as expected.
One option would be to inject it into an ITypeConverter
:
public class AutoMapperConfiguration : Profile
{
public AutoMapperConfiguration()
{
CreateMap<SourceModel, DestinationModel>().ConvertUsing<ExampleConverter>();
}
}
public class ExampleConverter : ITypeConverter<SourceModel, DestinationModel>
{
private readonly ICloudStorage _storage;
public ExampleCoverter(ICloudStorage storage)
{
// injected here
_storage = storage;
}
public DestinationModel Convert(SourceModel source, DestinationModel destination, ResolutionContext context)
{
// do conversion stuff
return new DestinationModel();
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<ICloudStorage, AzureStorage>();
services.AddAutoMapper();
}
回答2:
you may want to try this on your Startup.cs, if AddAutoMapper
is an an extension that you built, then add the code below to your extension.
public void ConfigureServices(IServiceCollection services)
{
var mapperConfiguration = new MapperConfiguration(mc =>
{
IServiceProvider provider = services.BuildServiceProvider();
mc.AddProfile(new AutoMapperConfiguration (provider.GetService<ICloudStorage>()));
});
services.AddSingleton(mapperConfiguration.CreateMapper());
}
回答3:
I found one solution to resolve this.
Create one list of types before add profile and pass it in the parameter.
public class AutoMapperConfiguration : Profile
{
private readonly ICloudStorage _cloudStorage;
public AutoMapperConfiguration(ICloudStorage cloudStorage)
{
_cloudStorage = cloudStorage;
// Do mapping here
}
}
public void ConfigureServices(IServiceCollection services)
{
var types = new List<Type>();
services.AddSingleton<ICloudStorage, AzureStorage>();
services.AddAutoMapper((provider, cfg) =>
{
var storage = new AutoMapperConfiguration(provider.GetService<ICloudStorage>());
types.Add(storage.GetType());
cfg.AddProfile(storage);
//others profiles
}, types);
}
来源:https://stackoverflow.com/questions/44229719/automapper-dependency-injection-with-parameters