Mapster如何将DB上下文注入映射配置



我需要使用DB上下文来映射基于Name属性的嵌套对象,这是一个字符串。我试图注入DB上下文映射配置,但我得到以下错误:

系统。MissingMethodException:不能动态创建实例的类型'ChatBotCore.Application.Bots.Common.MappingConfig'。原因:没有定义无参数构造函数。Less构造函数定义

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

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

相关内容

  • 没有找到相关文章

最新更新