.net Mapster如何将DB上下文注入Map配置

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

我需要使用数据库上下文来Map一个嵌套的对象,基于名称属性,这是一个字符串。我试图注入数据库上下文到Map配置,但我得到以下错误:
System.MissingMethodException:无法动态创建类型为“ChatBotCore.Application.Bots.Common. MappingConfig”的示例。原因:未定义无参数构造函数

public class MappingConfig : IRegister
    {
        private readonly IApplicationDbContext _context;

        public MappingConfig(IApplicationDbContext context)
        {
            _context = context;
        }

        public void Register(TypeAdapterConfig config)
        {
            config.NewConfig<Bot, GetBotsResult>()
                .Map(dest => dest.Channel, src => src.Channel.Name)
                .Map(dest => dest.NluServiceProvider, src => src.NluServiceProvider.Name);

             config.NewConfig<CreateBotCommand, Bot>()
                 .Map(dest => dest.Channel, src => GetChannelByName(src.Channel))
                 .Map(dest => dest.NluServiceProvider, src => GetNluServiceProviderByName(src.NluServiceProvider));

              config.NewConfig<UpdateBotCommand, Bot>()
                 .Map(dest => dest.Channel, src => GetChannelByName(src.Channel))
                 .Map(dest => dest.NluServiceProvider, src => GetNluServiceProviderByName(src.NluServiceProvider));
        }

         private async Task<NluServiceProvider> GetNluServiceProviderByName(string nluServiceProvider)
         {
             return await _context.NluServiceProviders.FirstAsync(x => x.Name.ToLower() == nluServiceProvider.ToLower());
         }

         private async Task<Channel> GetChannelByName(string channel)
         {
             return await _context.Channels.FirstAsync(x => x.Name.ToLower() == channel.ToLower());
         }
    }
9udxz4iz

9udxz4iz1#

public interface IMappingConfig: IRegister { /* interface for finding */ }
public class MappingConfig : IMappingConfig // use known interface here
{
    /* your code */
}

private static void RegisterMappers(IServiceCollection services)
{
    services.AddSingleton(TypeAdapterConfig.GlobalSettings);
    services.AddScoped<IMapper, ServiceMapper>();

    // inserting needed dependencies
    services.AddSingleton<IApplicationDbContext, ApplicationDbContext>(); 
    services.AddScoped<IMappingConfig, MappingConfig>();

    // now the work around, create a (temporary) service provider 
    // just for retrieving your mapping having all di done automatically
    var provider = services.BuildServiceProvider();

    TypeAdapterConfig.GlobalSettings.Apply(
        provider.GetService<IMappingConfig>() // this now works with di
    );
}

相关问题