3

I want to inject configuration object into Mapster. Below is the code.

    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 part:

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

The dependency inject only works for mapper config that does not inject the configuration object.

M. Ko
  • 563
  • 6
  • 31

1 Answers1

0

Mapster cannot dynamically create an instance of your mapping config class because it needs a parameterless constructor.

So to inject service into your mapping configuration, you do so by MapContext.Current.GetService<>()

Your code would look like so,

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}"));
    }
}

Here is a link to the wiki on dependency injection support

U.Shaba
  • 542
  • 5
  • 11