30

I would like to ask for 3 information here:

  1. 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 ?

  2. 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.

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

    1. it schould work similar to AspectJ and has similar syntax
    2. 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.
    3. should include all features of AspectJ. Support for generics.
    4. solution should be stable, widely used and mainteined.
    5. should offer weaving of binaries (so could be used ) or C# source code.
    6. 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.

Community
  • 1
  • 1
Rasto
  • 17,204
  • 47
  • 154
  • 245
  • I'm considering to make this comunity wiki question but I don't know how :( – Rasto Feb 15 '11 at 01:37
  • 1
    @drasto: CW is no longer possible, and in this instance, not desirable. – John Saunders Feb 15 '11 at 01:38
  • 2
    How did this get voted off-topic? This is perfectly acceptable. Maybe slightly subjective, but I think the OP has given enough criteria that it should be fine. – Gordon Gustafson Feb 15 '11 at 01:43
  • @Crazy: I think this is a good question for Programmers, not for SO. – John Saunders Feb 15 '11 at 01:56
  • @John I did not know about existence of Programers site before but now I checked it and I don't think its on wrong place. People offen ask questions about the technology that is the best for particular software developlment problem here. I did just that - I will use answer in my project (if there is any such solution for .Net). However I agree it could also be on Programers - but there the answers would be more like James Blank below... What I would really apriciate is just a answer: *there is this and that library, one of that may suit your needs because something** – Rasto Feb 15 '11 at 04:05
  • @drasto: personally, I don't think that "list of something and why" questions belong here. I think they barely belong on Programmers, but I trust that community to police itself. – John Saunders Feb 15 '11 at 20:27
  • @John Saunders: I considered that to be a good question for meta, so I asked it there: PLease feel free to state your opinion there: http://meta.stackexchange.com/questions/79835/does-list-of-something-and-why-questions-belong-to-so-and-if-not-then-where – Rasto Feb 18 '11 at 18:34

3 Answers3

18

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)

  1. 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?)

  2. check

  3. everything but language support

  4. check

  5. check - it is a post compile weaver

  6. 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:

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

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

  3. 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.

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

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

  1. 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

Roger Johansson
  • 22,764
  • 18
  • 97
  • 193
4

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

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • I haven't looked closely at PostSharp 2.0, but when I looked before it has very limited capabilities compared to AspectJ. – James Black Feb 15 '11 at 01:44
  • I'm not familiar with AspectJ - what does it do that PostSharp doesn't? – Adam Rackis Feb 15 '11 at 01:49
  • You may want to look at http://www.eclipse.org/aspectj/doc/released/progguide/index.html to learn more, but basically, I can have a program that I don't have the code for. I can then write code that will modify the application at runtime, to give it different behavior. You can also make these changes at compile-time, btw. So, I could have one C# class (in theory) and based on the assembly I include it could be a SOAP or REST service, or a controller for a WPF application, if AspectJ worked on .NET. – James Black Feb 15 '11 at 01:57
  • 1
    You can intercept calls to code you so not have the source for with PostSharp as well, we use that frequently to intercept calls to the .NET runtime for various reasons. One major advantage of PostSharp is that it does everything at compile time, which leads to higher build times, yes, but only to minimally higher runtime execution times compared to other AOP frameworks that wave during runtime. This is what sealed the deal for us + its developer friendly. – ntziolis Feb 15 '11 at 13:43
  • 1
    3. Generics are supported, 6. VS plugin exists as well, it will highlight weaved methods/classes, and will offer you click able hyper links right to the aspects – ntziolis Feb 15 '11 at 13:45
  • +1 for confirming 1. and for sample use of PostSharp – Rasto Feb 15 '11 at 15:20
0

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/

James Black
  • 41,583
  • 10
  • 86
  • 166
  • 5
    -1 I completely disagree, you are missing the point of AOP. AOP is completely different programing paradigm the difference is like between procedural programing and OO programing. It has *nothing* to do with limitation of the language. Any program that can be writen with AOP could also be written without it (as well as any program written in OOP could be written in procedural programing). AOP allows to add new functionality (aspect) to existing program easyly but you would be able to add it with pure Java or C# as well (or you can do it with extension methods, IronRuby and 10 more... – Rasto Feb 15 '11 at 03:40
  • ...technologies together). But the point is that with AOP you get well structured code that is modular and less like to intruduce bugs (programing-practise motivation -> same as motivation from procedural programing to OOP). You can replace one good AOP solution by 10 existing technologies that has to be leant and are not even ment for that purpose but you will and up with everything mixed together and not transparent at all. This applies to extending som application using AOP as well as to creating AOP aplication from scratch. – Rasto Feb 15 '11 at 03:50
  • @drasto - I spent years using AspectJ in order to make my code more flexible, but what I did with aspects can be done in other ways with what other languages offer, so there is less need for them. Domain specific languages allow us to have type-safe code that can be added to a program at runtime, in some languages, that will give you the modularity you are looking for. – James Black Feb 15 '11 at 11:02
  • I'm sorry but I cannot agree with suggestion that IronRuby, extension methods or anything else can replace AOP language for C# or any other language. AOP is (as we agree) new paradigm. A paradigm that is used both for creating new application (that have at least to aspects) that are not supposed to be adaptive and for those that are expected to to adapt to new needs over time. You seems to ignore the first case btw. As any other paradigm for writing programs it needs **good** programing language that implements that paradigm. IronRuby in combination with extension methods and I don't know... – Rasto Feb 18 '11 at 17:37
  • ...what else **are not a good programing language** in the fact all those technologies together are not programing language at all. You can use them to make your applications easy to adapt but that does not mean they are AOP language. What I was asking for in my original question here is AOP programing solution, not a way to create adaptive aplication. Anyway I think that with IronRuby etc. you cannot do what you could do with AOP. – Rasto Feb 18 '11 at 17:49
  • Here: http://www.google.com/url?sa=t&source=web&cd=3&ved=0CCcQFjAC&url=http%3A%2F%2Fciteseerx.ist.psu.edu%2Fviewdoc%2Fdownload%3Fdoi%3D10.1.1.115.8660%26rep%3Drep1%26type%3Dpdf&ei=kLBeTZHPDsiv8QPVyeBZ&usg=AFQjCNEurFqR2WfA2OC8MzykIH5rhxOGJQ&sig2=aUGajkXvfCfdIcrDt-IFsw you can read a paper from Gregor Kiczales who in the fact invented AOP about the idea behind it. There is also definition what is a AOP language. – Rasto Feb 18 '11 at 17:51
  • @drasto - I saying that am not IronRuby and other languages are AOP, but, the uses we have for AOP are not necessarily needed, as there are ways to get the same functionality by using different languages. If you want to just stay with Java then AOP may be needed to get the flexibility you wanted. If you want to see an article about writing AOP applications you can look at one of the papers that most influenced my thoughts on AOP: http://www.ibm.com/developerworks/java/library/j-aopwork7/index.html – James Black Feb 19 '11 at 01:19
  • @JamesBlack: I also disagree. Please read about obliviousness and what cross-cutting concerns exactly are. – Matthias Jun 25 '16 at 00:32