在启动时,将凭据提供程序和db上下文添加到服务集合中。将您的凭证提供者创建为作用域服务,并将db上下文添加到其构造函数中,以便可以从DI解析它。一旦提供者从依赖项注入中解析dbcontext,就可以将凭据提供者传递给bot,并在凭据提供者中执行逻辑,从db中检索凭据。
如果您需要比配置更健壮的东西,您可以选择创建一个botid解析器来解析每个请求的botid。。。也许可以在管道中添加一些查看管线值的内容。
public void ConfigureServices(IServiceCollection services)
{
//OtherServices
// add your db context to services
services.AddDbContext<YourDbContext>();
// setup your credential provider to resolve on every request -scoped
services.AddScoped<ICredentialProvider, MultiCredentialProvider>();
// optional create a BotIdResolver that can retrieve the botid at runtime per request for example resolve it from the route
services.AddScoped<IBotIdResolver, ConfigIdResolver>();
}
public class MultiCredentialProvider : ICredentialProvider
{
private readonly IConfiguration _configuration;
private readonly YourDbContext _db;
private readonly BotIdResolver _resolver;
public MultiCredentialProvider(IConfiguration configuration, YourDbContext db,IBotIdResolver botIdResolver = null)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_db = db;
_resolver = botIdResolver;
}
// optional replace with botIdResolver
public int BotId => _configuration.GetBotId();
public async Task<bool> IsValidAppIdAsync(string appId)
{
// optional use botIdResolver
//var id = _resolver.GetId();
// work with dbcontext
//_db.
}
}