9

In my sample code I have the following:

namespace WebUx.Filters
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
    {
        private static SimpleMembershipInitializer _initializer;
        private static object _initializerLock = new object();
        private static bool _isInitialized;

        public override void OnActionExecuting(ActionExecutingContext filterContext)

Can someone explain to me how this works? Does this automatically get attached to every class method or just the controller classes? I am using both MVC and also the web api. Will it also attach to web api methods?

4 Answers4

10

AttributeUsage isn't specific to MVC. It describes where and how an attribute may be used.

In most (all?) cases, the compiler will enforce these constraints.

However, nothing "magical" happens; you still need to decorate the class/member with the attribute for it do anything. In other words, it doesn't automatically get applied to all types or members.*

See also: http://msdn.microsoft.com/en-us/library/tw5zxet9(v=vs.110).aspx

*The Inherited property does provide a very limited amount of automation. See How does inheritance work for Attributes?.

Community
  • 1
  • 1
Tim M.
  • 53,671
  • 14
  • 120
  • 163
  • i have a small doubt, in the above question we have a sealed class and the attributeUsage has Inherited = true property. How can this work, when sealed stops the class from getting inherited, please explain.. thank you – Lijin Durairaj Dec 05 '16 at 17:19
  • 1
    @LijinJohn - the attribute itself is sealed, but the `Inherited` property describes how the attribute behaves when applied to *other* classes. Those other classes may not be sealed. – Tim M. Dec 05 '16 at 17:46
1

Determines how a custom attribute class can be used. AttributeUsage is an attribute that can be applied to custom attribute definitions to control how the new attribute can be applied.

So it basically gives the compiler some extra information about the attribute class you will implement.

You have a few excellent examples at: http://msdn.microsoft.com/en-us/library/tw5zxet9(v=vs.100).aspx

Freeman
  • 5,691
  • 3
  • 29
  • 41
0

It does exactly the same thing as in all other types of applications (no special MVC behavior) - specifies where particular attribute can be used.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

AttributeUsage dictates where and how the attribute can be used. So your example can be applied to a class or to a method, but it can only be applied once per entity.

It won't be automatically attached to any classes. You'll have to explicitly do that yourself.

See the C# programming guide on AttributeUsage: http://msdn.microsoft.com/en-us/library/tw5zxet9(v=vs.80).aspx