Why does my .NET Attribute not perform an action?
Asked Answered
B

3

5

I've created a simple Attribute:

[AttributeUsage(AttributeTargets.Method)]
public class InitAttribute : System.Attribute
{
    public InitAttribute()
    {
        Console.WriteLine("Works!");
    }
}

and I apply it to a simple method:

static class Logger
{
    public static string _severity;

    public static void Init(string severity)
    {
        _severity = severity;
    }

    [Init()]
    public static void p()
    {
        Console.WriteLine(_severity);
    }
}

What is going on is pretty straightforward. Only, I expect the attribute to perform an action (printing "Works!"), but this does not happen.

Additionally, printing "Works!" is of course just for debugging purposes: I'd like to access the instance's property _severity (to check if is != null, for example), but everything I keep reading about regarding attributes (that is pretty new to me) is about accessing the class' methods or properties and so on via reflection. Once I've evaluated _severity, how can I modify the behavior of the decorated method (in this case, raise an exception "Logger is not initialized" and do not execute it)?

Any help appreciated.

Brisco answered 22/7, 2009 at 12:42 Comment(0)
F
12

If you need to perform an action as control enters a method, you should look at aspect-oriented programming and frameworks such as PostSharp. Attributes are not designed to perform anything by themselves. They are just a bunch of data (or metadata if you will) attached to stuff in IL assemblies that can be queried at runtime.

Finitude answered 22/7, 2009 at 12:44 Comment(1)
One thing causing users to ask this question is the way that frameworks such as ASP.Net MVC add hooks to attributes in things like ActionFilterAttribute, so that they appear to do something. This encourages people to try to get normal attributes to be more proactive.Surculose
S
1

Attributes only allow decoration of types and members, but the attribute itself cannot acces the decorated object. You will have to use the constructor parameters of the attribute to pass in any data you require to work with within the attribute.

If you wish to use attributes to automatically alter the behaviour of their target objects, you will have to look at AOP solutions like PostSharp.

Shabbir answered 22/7, 2009 at 12:48 Comment(0)
S
1

The attribute is never actually instantiated and so its constructor is never called. The attribute remains as meta-data until you use reflection to retrieve it. As has been mentioned previously what you are after is an Aspect Oriented Programming tool. PostSharp works by altering the assembly as a post-build step. If you are using the Castle Windsor or Unity Inversion of Control Containers they both offer AOP capabilities as well.

Simmonds answered 22/7, 2009 at 13:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.