Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ASP.NET Core MVC filter singleton?

I have an AuthorizationFilter as follows:

public class AuthorizationFilterAttribute : Attribute, IAuthorizationFilter
{
    public AuthorizationFilterAttribute()
    {
        //Constructor of AuthorizationFilter will be called one time
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        //OnAuthorization method will be called per http request
    }
}

I found the constructor of AuthorizationFilter will just be called one time during the whole ASP.NET Core application lifetime. But its OnAuthorization method will be called per HTTP request.

Does it mean all filters (including IAuthorizationFilter,IActionFilter,IResourceFilter,IExceptionFilter etc) in ASP.NET Core MVC are singletons, which means they will be created just one time during ASP.NET Core application lifetime?

like image 775
Scott.Hu Avatar asked Apr 23 '26 08:04

Scott.Hu


1 Answers

It depends on the IFilterFactory.IsReusable property that is associated with your filter.

When the IFilterProvider (which by default is DefaultFilterProvider) is about to provide the desired instance, it first checks whether the filter implements IFilterFactory as well:

  • If it does, it uses the filter's own IsReusable property to determine the lifetime of the instance.
  • If not, it assumes the filter is reusable and IsReusable is set to true.

In the case of your custom AuthorizationFilterAttribute, since you don't implement IFilterProvider, it's indeed considered as reusable and will be created only once.

See Source

like image 100
haim770 Avatar answered Apr 24 '26 22:04

haim770



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!