I have a .NET core project and am trying to create a custom policy using AuthorizationOptions as shown in the documentation located here:
ASP.NET.Core Authorization - Dependency Injection in requirement handlers
The examples show setting up an authorization requirement with 1 parameter - a simple int value. My custom requirement requires a string parameter as well as a DbContext object. I want to inject the DbContext into the requirement's constructor at runtime. I am using the Autofac container. I'm not sure how I can achieve this - have tried several approaches and nothing is working so far.
Here is my custom requirement:
public UserNameRequirement(string username, MyDbContext context)
{
_userName = username;
_dbContext = context;
}
When setting up the authorization options in Startup.cs ConfigureServices method the documentation shows you register this like so:
services.AddAuthorization(options =>
{
options.AddPolicy(
"UserNamePolicy",
policy => policy.Requirements.Add(new UserNameRequirement("admin", ** want to resolve and inject my DbContext here **)));
}
I am not sure how to achieve this. I've seen this post which is a similar question but it's using ASP.NET 5 and that syntax doesn't work with .net core:
MyDbContext
in theUserNameRequirement
class? – Woman