I am using a MultiCredentialProvider
that implements the Microsoft.Bot.Connector.Authentication.ICredentialProvider
interface. It works with static values but as soon as I try to pass a repository which uses a DbContext
to retrieve my bot credentials, it fails with the following message.
System.InvalidOperationException: An attempt was made to use the context while it is being configured. A DbContext instance cannot be used inside OnConfiguring since it is still being configured at this point. This can happen if a second operation is started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
This is caused because the repository should be scoped and not just passed to an object to use in a later stage. The repository is resolved in the ConfigureServices
method of the Startup
class.
var sp = services.BuildServiceProvider();
var repository = sp.GetService<SomeRepository>();
services.AddBot<SomeBot>(options => {
options.CredentialProvider = new MultiCredentialProvider(configuration, repository);
})
The question is, how can I resolve the service on demand to avoid this error? Is it possible to resolve the whole CredentialProvider, so I can make use of constructor injection? Anything else that I am missing here?
--
Update:
As a temporary workaround, I first get the credentials list from the database, then construct the object and pass the credentials to the MultiCredentialProvider
constructor. The only problem with this is that everything is assigned at startup and cannot be changed at a later time. Still looking for better solutions.
I've ended up writing a Func that gets invoked when the credentials are required. The values are cached so it's not an expensive lookup.
public class MultiCredentialProvider : ICredentialProvider
{
private readonly IConfiguration _configuration;
private readonly Func<Task<List<MultiBotCredential>>> _botCredentialsFunc;
public MultiCredentialProvider(IConfiguration configuration, Func<Task<List<MultiBotCredential>>> botCredentialsFunc)
{
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
_getBotCredentialsFunc = botCredentialsFunc;
}
public int BotId => _configuration.GetBotId();
public async Task<bool> IsValidAppIdAsync(string appId)
{
var botCredentials = await _botCredentialsFunc.Invoke();
var credential = botCredentials.FirstOrDefault(x => x.BotId == BotId);
if (credential == null)
{
return false;
}
return credential.AppId.Equals(appId, StringComparison.InvariantCultureIgnoreCase);
}
...
}