我想注入配置对象到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器配置。
1条答案
按热度按时间iszxjhcz1#
Mapster无法动态创建Map配置类的示例,因为它需要无参数构造函数。
因此,要将服务注入到Map配置中,可以通过
MapContext.Current.GetService<>()
执行你的代码看起来像这样,
以下是dependency injection support上的wiki链接