具有参数的AutoMapper依赖项注入

编程入门 行业动态 更新时间:2024-10-24 07:23:28
本文介绍了具有参数的AutoMapper依赖项注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

错误:AutoMapperConfiguration没有无参数的构造函数

Error: No parameterless constructor for AutoMapperConfiguration

我正在使用nuget包 automapper DI

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 }

如何将自动映射器DI与参数一起使用?

How do I use the automapper DI with parameters?

推荐答案

我认为您无法将DI参数添加到Profile.这种情况背后的部分逻辑可能是这些实例仅实例化一次,因此通过AddTransient注册的服务将无法达到预期的行为.

I don't think you are able to add DI parameters to Profiles. Part of the logic behind this may be that these are only instantianted once, so services registered through AddTransient would not behave as expected.

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

更多推荐

具有参数的AutoMapper依赖项注入

本文发布于:2023-08-02 11:45:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1277540.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   AutoMapper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!