Search code examples
c#asp.net-mvcattributesaction-filter

Same instance of the Attribute is used for multiple method call


I am creating an Action Filter in MVC, I have created a new Attribute that inherits from ActionFilterAttribute class, and implemented the OnActionExecuted method. Then I have decorated an action with this new attribute. When I call the action for the first time everything is fine, the constructor of the Attribute is called then the OnActionExecuted method. When I call this same action for the second time, I find that the constructor of the Attribute was not called, and the state of internal attribute members that were set during the first call of the Action is still preserved, which clearly means that the same instance of the Attribute is used for all calls to the action. Is there a way to force a new instance for each attribute call?


Solution

  • When you attach an attribute to a type, member, parameter etc. you are annotating the metadata of the attribute target. In your case you apply an attribute to a method, so it is attached on the metadata level to the method, not to the instances the method is called on. That means you will get a new attribute instance for each method you apply it to, not for each method and each instance of the class the target method is defined on.

    Since metadata has no state that can change, the attribute, if correctly used, has no changing state either. You can not change the way attributes work, so you have to implement your attribute in a way that it does not rely on an internal state.