0

I am trying with the Debugger to stop when a method attribute is invoked, but I am never seems to get to the break point. Am I missing something here?

[SecurityImpl("test")]
public void test()
{

}

[AttributeUsage(AttributeTargets.All)]
public class SecurityImplAttribute : Attribute
{
    public SecurityImplAttribute(string test)
    {
        //Break Point Here    
    }
 }
Filburt
  • 17,626
  • 12
  • 64
  • 115
SexyMF
  • 10,657
  • 33
  • 102
  • 206
  • 1
    Duplicate: http://stackoverflow.com/questions/9166996/when-are-attribute-objects-created – roken Jul 17 '12 at 12:20

3 Answers3

2

Attributes are only metadata. They aren't actually created as instances unless you use reflection (GetCustomAttributes). You cannot use attributes to add arbitrary code calls, unless you use an AOP framework such as PostSharp, or are using a framework that checks for specific categories of attributes and instantiates/invokes them explicitly (like ASP.NET MVC does).

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • I know that in Java, Spring can invoke injected objects, do you know if it can be done with Spring.net? thanks – SexyMF Jul 17 '12 at 12:22
1

Attributes are only decorators and they do not execute by .net framework.

ZafarYousafi
  • 8,640
  • 5
  • 33
  • 39
1

Attrubutes are just metadata for your code. They are not executed automatically. If you want to use some metadata, you should get it manually and execute it. In your case constructor of attribute will be executed when you'll try to get method custom attributes:

object[] attributes = methodInfo.GetCustomAttributes(true);

If you want some aspects to be executed automatically, when you invoke method, then you can use some AOP framework, like PostSharp. Here is an example of aspect creation, which executes some actions on method call:

[Serializable]
public class SecurityImplAttribute : OnMethodBoundaryAspect
{
   public override void OnEntry(MethodExecutionArgs args) 
   { 
      // this code will be executed on method call
   }   
}

When you apply this attribute to some method, PostSharp will read method's metatada during compilation, and if aspect will be found, PostSharp will inject your code right into binaries.

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459