Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to apply an attribute to a method that executes first?

Without using a library like PostSharp, is there a way to set up a custom attribute that I can have logic in that when attached to a method, will execute PRIOR to entering that method?

like image 427
Brian David Berman Avatar asked Dec 03 '25 10:12

Brian David Berman


1 Answers

No; attributed are not intended to inject code. Tools like postsharp get around that with smoke and mirrors, but without that: no. Another option might be a decorator pattern, perhaps dynamically implementing an interface (not trivial by any means). However, adding a utility method-call to the top of the method(s) is much simpler, and presumably fine since if you have access to add attributes you have access to add a method-call.

Or put another way: tools like postsharp exist precicely because this doesn't exist out-of-the-box.

// poor man's aspect oriented programming
public void Foo() {
    SomeUtility.DoSomething();
    // real code
}

In some cases, subclassing may be useful, especially if the subclass is done at runtime (meta-programming):

class YouWriteThisAtRuntimeWithTypeBuilder : YourType {
    public override void Foo() {
        SomeUtility.DoSomething();
        base.Foo();
    }
}
like image 73
Marc Gravell Avatar answered Dec 05 '25 22:12

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!