I have a Web API project where I intend on using an attribute that inherits from ActionFilterAttribute
to do logging in a standardized fashion. As part of that logging, I want to extract some values from HttpActionContext
in the OnActionExecuting
method. I would then want to refer to these as part of OnActionExecuted
. I have specified [AttributeUsage(AttributeTargets.Class)]
for this attribute. My assumption is that my custom attribute would be instantiated in concert with the class it is applied to, and have the same lifetime as the class to which the attribute is applied. I can't find anything to concretely back this up. I've done some testing and that seems to be how it works but I worry that my test is too limited. I'm assuming that multiple calls to the same controller will generate new instances of that controller and thus new instances of the attribute. I'm basically worried about the thread safety of the data I retrieve as part of OnActionExcecuting
.
Anyone know any resources or links that can confirm or deny my assumptions?
It depends on what you are going to use.
Attributes (filters) in Web API are cached (filter pipeline is private readonly Lazy<Collection<FilterInfo>> _filterPipeline;
and initialized only once). see here
Therefore if you initialize something in the attribute's constructor, it will remain the same on subsequent executions.
However, the HttpActionContext
is created created for every request from HttpControllerContext
and HttpActionDescriptor
and then passed on to each of the cached filters in the pipeline. see here
As a result, even though the instances of the filters are reused, the value of the context in the methods is specific to the specific request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With