You can use ServiceFilterAttribute for this purpose. The service filter attribute allows the DI system to take care of instantiating and maintain the lifetime of the CustomAuthorizeFilter
filter and any necessary services.
Example:
// register with DI services.AddScoped<ApplicationDbContext>(); services.AddTransient<CustomAuthorizeFilter>(); //------------------ public class CustomAuthorizeFilter : IAsyncAuthorizationFilter { private readonly ApplicationDbContext _db; public CustomAuthorizeFilter(ApplicationDbContext db) { _db = db; } public Task OnAuthorizationAsync(AuthorizationContext context) { //do something here } } //------------------ [ServiceFilter(typeof(CustomAuthorizeFilter))] public class AdminController : Controller { // do something here }
source share