Using Attributes to Call Methods

后端 未结 3 1718
伪装坚强ぢ
伪装坚强ぢ 2021-02-07 12:38

I have various individual methods which all need to perform the same functions before continuing on with their own implementation. Now I could implement these functions in each

相关标签:
3条回答
  • 2021-02-07 12:51

    You can use PostSharp, it is aspect-oriented framework for .NET, it seems quite easy to use:

    static void Main(string[] args)
    {
        Foo();
    }
    
    [IgnoreMethod(IsIgnored=true)]
    public static void Foo()
    {
        Console.WriteLine("Executing Foo()...");
    }
    
    [Serializable]
    public class IgnoreMethodAttribute : PostSharp.Aspects.MethodInterceptionAspect
    {
        public bool IsIgnored { get; set; }
    
        public override void OnInvoke(PostSharp.Aspects.MethodInterceptionArgs args)
        {
            if (IsIgnored)
            {
                return;
            }
    
            base.OnInvoke(args);
        }
    }
    

    Method-Level Aspects feature is available in the free edition: http://www.sharpcrafters.com/purchase/compare

    Run-Time Performance:

    Because PostSharp is a compiler technology, most of the expensive work is done at build time, so that applications start quickly and execute fast. When generating code, PostSharp takes the assumption that calling a virtual method or getting a static field is an expensive operation. Contrary to rumor, PostSharp does not use System.Reflection at run time. http://www.sharpcrafters.com/postsharp/performance

    0 讨论(0)
  • 2021-02-07 13:05

    I don't think you can do this with attributes only, because they are not executed by the runtime if you're not actively doing something with them. A lightweight approach would be Ninject with Interceptions extension, it is a framework, but a very thin one, and one you might already be using for DI anyway.

    Another option, but a bit more involved, could be based on MEF, and then you can use attributes and do something during with them during activation.

    0 讨论(0)
  • 2021-02-07 13:10

    You're right, it sounds a lot like AOP.
    What you're after sounds like compile time weaving? I.e. the attribute is turned into additional code by the compiler.
    You could look at how to implement this...
    Generating additional code through a custom attribute
    http://www.cs.columbia.edu/~eaddy/wicca/ &
    http://www.sharpcrafters.com/aop.net/compiletime-weaving
    all refer to tools and techniques for doing this.

    Or you could use an AOP framework. IMHO, you should look at AOP frameworks.

    0 讨论(0)
提交回复
热议问题