Aspect Oriented Programing (AOP) solutions for C# (.Net) and their features

I would like to ask for 3 information here:

  • There is no integrated solution for Aspect Oriented Programing (AOP) in C# (.Net) from Microsoft is that correct ? Is there any such solution under development or planned ?

  • What solutions are there that allow Aspect Oriented Programing (AOP) to be used in C# (.Net) ? What are they advantages/disadvantages ? I haven't find any comprihensive list that would contain all avatable options and some information for me to decide which is the one to use. The closest is this list.

  • What is (in your opinion) the best AOP solution for C#(.Net) considering following criteria:

  • it schould work similar to AspectJ and has similar syntax
  • simplicity of use: no XML configuration should be needed - just write some regular classes, some aspect classes and compile to weave it all together, then run.
  • should include all features of AspectJ. Support for generics.
  • solution should be stable, widely used and mainteined.
  • should offer weaving of binaries (so could be used ) or C# source code.
  • GUI tool for visualising (or even better - plugin to VS) is an advantage.
  • I think that if something fullfils most of criteria in 3. then it is a candidate for a generaly used solution. And I cannot find anywhere if some of existing solutions fits to my needs.


    As Adam Rackis points out, Post# is the way to go, it is as close you will get to AspectJ on the .NET platform.

    Main differences is obviously that AspecJ has language support for aspects while Post# is a post compile weaver for .NET assemblies. (thus no language integration)

    However, Post# can use join points such as field access, try catch blocks, both calls and functions (that is, caller and callee)

  • No not even close, AspectJ is a language, Post# can use custom pointcuts but the most common is to use attributes to decorate methods to be pointcutted(eh..grammar?)

  • check

  • everything but language support

  • check

  • check - it is a post compile weaver

  • limited, the weaver will generate intellisense information and show what methods have been affected

  • If you want a .NET language that supports aspects, check out http://aspectsharpcomp.sourceforge.net/samples.htm

    Regarding different approaches, there are a few:

  • Post compile weaving , this is what Post# does. It simply mangles the .NET assembly and injects the aspect code.

  • Real Proxy / MarshallByRefObject. Based on remoting infrastructure. Requires your classes to inherit from a base class. Extremely bad performance and no "self interception"

  • Dynamic Proxy. This is what my old library NAspect used. you use a factory to create a subclass of the type on which you want to apply aspects. The subclass will add mixin code using interfaces and override virtual methods and inject interceptor code.

  • Source code weaving. As the name implies, it transforms your source code before compilation.

  • [edit] I forgot to add this one to the list:

  • Interface proxies Similar to Dynamic Proxy, but instead of applying the interception code to a subclass, the interception code is added to a runtime generated interface proxy. That is, you get an object that implements a given interface, this object then delegates each call to any of the interface methods first to the AOP interception code and then it delegates the call to the real object. That is, you have two objects at play here, the proxy and the subject(your real object).
  • Client -> Interface Proxy -> AOP interception -> Target/Subject

    This is AFAIK what Spring does.

    1) and 3) are the most common. They both have pros and cons:

    Post Compilation:

    Pros:

  • Can point cut pretty much everything, static , sealed, private
  • Objects can still be created using "new"
  • Cons:

  • Can not apply aspects based on context, that is , if a type is affected, it will be affected for the entire application.

  • Pointcutting private, static, sealed constructs may lead to confusion since it breaks fundamental OO rules.

  • Dynamic Proxy:

    Pros:

  • Contextual, one typ can have different aspects applied based on context.

  • Easy to use, no configuration or build steps.

  • Cons:

  • Limited pointcuts, only interface members and virtual members can be intercepted

  • must use factory to create objects


  • 1 - Correct

    2 - PostSharp is an outstanding AOP library for C#

    3 - I don't know how AspectJ works, but with PostSharp you simply define your aspects as attributes, and then decorate your methods with said attributes.

    Here's an example of an aspect that wraps a method call with a try catch, and logs any exceptions that get thrown:

    [Serializable]
    public class ErrorAspectAttribute : OnMethodBoundaryAspect {
        private bool Notify;
    
        public ErrorAspectAttribute(bool notifyUser = true) {
            this.Notify = notifyUser;
        }
    
        public override void OnException(MethodExecutionEventArgs args) {
            ErrorLoggerUtil.LogException(args.Exception);           
    
            if (Notify)
                MessageBox.Show("An error has occurred.  Please save blah blah blah", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    
            args.FlowBehavior = FlowBehavior.Return;
        }
    }
    

    So point by point

    1 - I don't know

    2 - check

    3 - I don't know 4 - check

    5 - check (pretty sure)

    6 - no - not sure how you would use a GUI for visualizing aspects like this


    The problem is that you are comparing different languages and trying to force square pegs into round holes.

    For Java AspectJ fills a need due to limits in the language, but .NET doesn't necessarily have these limitations, as the JVM doesn't, but Java does.

    For example, you can use IronPython or IronRuby (in addition to others) to write assemblies that are very dynamic, so you can write a DSL (domain specific language) that will enable a user to add in code that is not XML, but will change how the program operates.

    You can use extension methods in C# to change the behavior by swapping out assemblies, so you have an assembly that have extensions that log to a file, then you swap that assembly for another one with the same namespace that will send the data to a webservice, or do a noop.

    But, there are limitations to this that may be hard to overcome, such as being able to use one aspect to do something in every function called, such as using cflow (http://www.eclipse.org/aspectj/doc/released/progguide/semantics-pointcuts.html), but that may be because I haven't thought enough about how to do it.

    My point is not to give a complete explanation of how .NET doesn't need AspectJ, but to show that there are ways to get the behavior you may expect without using AOP.

    For apps running on the JVM you can use Groovy, Clojure, JRuby and Scala, for example, to work around the limitations of Java.

    UPDATE:

    I was hoping to keep my answer shorter, but some understanding of AOP may be useful to add context to my answer.

    Aspect Oriented Programming (AOP) is a different programming paradigm, for functionality that cuts across classes, such as logging. Logging is a common situation, where you may want to log all SQL queries being used, so, rather than copying code from place to place, you put it in one place and it gets put into everywhere you specify, so, if you decide later to change where the logging goes, you change it in one place.

    But with AspectJ there are more options. For example, you sell a program that stores passwords. Company A uses IDEA, company B uses AES. In order to adapt you change the code that is used at runtime so you don't have to risk recompiling the code and introducing new bugs, and it is changed, so that whenever someone calls getPassword() the new code is used to decrypt it.

    You can also add functionality to an existing class, so I would put methods into interfaces so that everything that used that interface now had access to the functions, so the methods were now concrete, in the interface.

    But, by using other languages that are on the .NET and JVM you can do all of these, with the same modularity, by carefully picking which language to use. For example, in Java you can access classes written in Groovy or Scala, so you can get more flexibility with these languages and still have the main app in Java.

    In C# you can use F#, IronPython or IronRuby, for example, to get this functionality, or, for some cases you can use C#.

    So the need for aspect oriented programming is lessened due to these dynamic, or strongly-typed functional languages, being available on these virtual machines, but, you trade the complexity of working with aspects with having a multi-language solution.

    For more on AOP, IBM had some incredible articles about using it, with their AOP@Work series: http://www.ibm.com/developerworks/views/java/libraryview.jsp?search_by=AOP@work:

    For some thoughts on AOP on .NET you can read Code mangling AOP vs. Runtime Proxy AOP , http://rogeralsing.com/2008/01/08/code-mangling-aop-vs-runtime-proxy-aop/

    链接地址: http://www.djcxy.com/p/95170.html

    上一篇: Python中的面向方面编程(AOP)

    下一篇: 针对C#(.Net)的面向方面编程(AOP)解决方案及其特性