.net Mapster如何将配置对象注入类型配置

0sgqnhkj  于 2023-04-22  发布在  .NET
关注(0)|答案(1)|浏览(240)

我想注入配置对象到Mapster.下面是代码.

public class DownloadLinkMappingConfig : IRegister
    {
        private readonly IConfiguration Configuration;

        public DownloadLinkMappingConfig(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void Register(TypeAdapterConfig config)
        {
            config.NewConfig<DownloadLink, DownloadLinkImage>()
                .Map(d => d.Id, s => s.Id)
                .Map(x => x.CompanyId, y => y.CompanyId)
                .Map(x => x.Name, y => y.Name)
                .Map(x => x.Url, y => y.Url)
                .Map(target => target.Image, source => Configuration.GetValue<string>($"DownloadLinkImages:{source.Name}"));
        }
    }

DI部分:

var typeAdapterConfig = TypeAdapterConfig.GlobalSettings;
typeAdapterConfig.Scan(Assembly.GetExecutingAssembly());
services.AddSingleton<IMapper>(new Mapper(typeAdapterConfig));

依赖注入仅适用于不注入配置对象的Map器配置。

iszxjhcz

iszxjhcz1#

Mapster无法动态创建Map配置类的示例,因为它需要无参数构造函数。
因此,要将服务注入到Map配置中,可以通过MapContext.Current.GetService<>()执行
你的代码看起来像这样,

public class DownloadLinkMappingConfig : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        config.NewConfig<DownloadLink, DownloadLinkImage>()
            .Map(d => d.Id, s => s.Id)
            .Map(x => x.CompanyId, y => y.CompanyId)
            .Map(x => x.Name, y => y.Name)
            .Map(x => x.Url, y => y.Url)
            .Map(target => target.Image, source => MapContext.Current.GetService<IConfiguration>().GetValue<string>($"DownloadLinkImages:{source.Name}"));
    }
}

以下是dependency injection support上的wiki链接

相关问题