2017-05-28 125 views
1

Error: No parameterless constructor for AutoMapperConfigurationAutoMapper依赖注入参数

我使用的NuGet包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 
} 

如何使用带参数的automapper DI?

+0

也许[这](https://stackoverflow.com/a/40275196/6583901)帮助 – NtFreX

+1

@ Dr.Fre不允许在automapper构造 –

+0

@MartinDawson是正确的参数。您只能注入自定义解析器和转换器。 – efredin

回答

0

我不认为您可以将DI参数添加到Profile s。部分逻辑背后的逻辑可能是这些只是一次实例化,因此通过AddTransient注册的服务不会像预期的那样运行。

一种选择是将其注入到一个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(); 
} 
1

你可能想试试这个在您的Startup.cs,如果AddAutoMapper是你建立了一个扩展,然后添加代码下面是你的扩展。

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()); 
    } 
+0

'services.AddAutoMapper'是问题中链接的NuGet包中的一种方法。 https://www.nuget.org/packages/AutoMapper.Extensions.Microsoft.DependencyInjection/ –

+0

我不确定,因为我在我的所有.net核心项目上广泛使用automapper,并且我没有或没有包含任何这样的语句。 。为了配置automapper,我所有/必须做的就是上面的那几行,我说IMapper注入到我的类的构造函数中,然后使用它。 – Jaya

+0

我只是回答“如果AddAutoMapper是您构建的扩展”部分 - 我们知道在这种情况下它不是定制的。 –