I am implementing an auth provider for .net core web api. The "auth" stuff is in a separate project, and has a delegate to the main project. This delegate is used for retrieving the "secret" from a public access id.
public delegate string RetrievePrivateKey(string publicKey);
This is set in the Startup.cs file like so:
options.GetPrivateKey += Utilities.APIAccess.GetPrivateKeyFromPublic;
My issue, is that the method NEEDS the database context in order to do the lookup. What would the best way to accomplish this be? The DbContext is a mysql context, with the connection string set via the appsettings.json. For the most part, everything is DI.
For reference, the "GetPrivateKeyFromPublic" method looks like this:
//This does not work, as it isn't grabbing the options/etc. Was just trying various things I read.
public static string GetPrivateKeyFromPublic(string publicKey)
{
DbContextOptions<DirectionsContext> options = new DbContextOptions<DirectionsContext>();
DirectionsContext ctx = new DirectionsContext(options);
DeviceService service = new DeviceService(ctx);
if (publicKey == "<default public>")//testing
return "<default private>";//testing
return service.GetPrivateKeyFromPublicKey(publicKey);
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddControllers();
services.AddDbContext<DirectionsContext>(options => options.UseMySql(Configuration.GetConnectionString("Development")));
services.AddMemoryCache();
services.AddSingleton<HmacHandler>();
services.AddSingleton<HmacOptions>();
services.AddAuthentication(App.Security.HmacDefaults.AuthenticationScheme).AddHmac(options =>
{
options.AuthName = "HMAC-SHA256";
options.CipherStrength = HmacCipherStrength.Hmac256;
options.EnableNonce = true;
options.EnableDeviceOS = true;
options.RequestTimeLimit = 5;
options.GetPrivateKey += Utilities.APIAccess.GetPrivateKeyFromPublic;
options.GetDeviceOS += Utilities.DeviceIdentify.GetDeviceOSFromUserAgent;//Utilities.DeviceUtility.GetDeviceOSFromUserAgent;
});
question from:
https://stackoverflow.com/questions/65854308/access-dbcontext-in-static-method-that-is-being-used-as-a-delegate 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…