user1464139
user1464139

Reputation:

What does the AttributeUsage do in MVC4

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?

Upvotes: 11

Views: 11538

Answers (4)

Tim M.
Tim M.

Reputation: 54378

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?.

Upvotes: 12

Matt Hotstone
Matt Hotstone

Reputation: 46

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

Upvotes: 0

Freeman
Freeman

Reputation: 5801

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

Upvotes: 1

Alexei Levenkov
Alexei Levenkov

Reputation: 100547

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

Upvotes: 0

Related Questions