This is tricky to answer, because AuthorizeAttribute
is both an Attribute
and an IAuthorizationFilter
.
In the context of an Attribute
, it is loaded when GetAttributes() is called the first time by the MVC framework. Attributes are meta-data, so it shouldn't be surprising if this is loaded before the debugger is attached.
In the context of an IAuthorizationFilter
, it depends on how the filter is registered. If registered as a global filter:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomAuthorizeAttribute());
filters.Add(new HandleErrorAttribute());
}
}
Then it is clearly instantiated during the startup of the MVC application, and in this case the filters collection is static so is only instantiated once per startup.
If the filter is placed as an attribute on a controller or action method, that's when things get more confusing. When an action is run, the MVC framework loads any attributes that pertain to that action method using the FilterAttributeFilterProvider
and executes them. In this case, there is an instance that is loaded as a IAuthorizationFilter
which scans for another instance of the same class that is an Attribute
.
If you need to explicitly control lifetime of the filter, then you can build your own IFilterProvider
that can do just that.
But there is no way to control the lifetime of an attribute. You should just assume that it is always loaded as a singleton and there is no way to create or destroy it.
The default behavior of AuthorizeAttribute
(as a filter) scans for another instance of AuthorizeAttribute
(as an attribute) in order to read the user/group metadata that it contains. The filter does the heavy lifting, the attribute is just a marker. If this is too confusing, you can separate them into 2 separate classes as per Passive Attributes.