More on AOP scenarios

The big scenario that always comes up WRT AOP programming is logging. I agree that that whole feature space – which I’ll lump into the “instrumentation” bucket – is a good scenario, though AOP is obviously not the only the way to approach it.

What are the other scenarios? If you can give me an example in code on what you would do with this kind of support (or what people are already doing with it in the Java space), that would be helpful. It seems that the examples I’m looking at are all related to logging.

Comments (19)

  1. Simon Smith says:

    Security is another I’ve heard mentioned.

  2. I guess I immediately think of the MTS/COM+ stuff: automatic transaction control, object pooling, JITA, …

  3. Sam Wu says:

    What about using AOP for the Observer Pattern?

  4. Marc says:

    I could be a bit confused, and indeed ‘logging’ may refer to my requirements, but I’d like to be able to treat methods and properties as first class objects (as in the prior post comment) for firing events, instead of continued code duplication.

  5. Hi Eric,

    Have a look at papers available here, for example. They describe various scenarii where Aspect Oriented Programming can be advantageously exploited.

  6. Hillard says:

    Look under the user samples on GotDotNet under "Automatic Exception Handling".

  7. Authentication and authorization, I would like some centralized way of authenticate users trying to *invoke* business components methods and then find out if they indeed have the privilege. It would be great if this concern could be changed (say from Active Directory driven to application provided tables) with minimum changes to the invocation *and* invoked logic.

  8. RichB says:

    All the AOP scenarios are easy to find – just speak to the SQL Server team and find out the scenarios people use Triggers for. In my mind, AOP and Triggers are very similar technologies – they are actions that occur out of sequence with the normal flow.

    I find Triggers abhorent.

  9. Justin Rudd says:

    I’ve never done AOP with Java, but I used ContextBoundObject to do security and caching.

  10. John Rusk says:


    I was thinking about this yesterday, after posting a couple of comments to your first thread on this subject. I find myself wishing that I could do this:

    public void SomeMethod()


    using(MagicMethodContext mc = new MagicMethodContext(SecurityLevel.EndUser))


    //method body goes here

    //mc.Transaction access a transaction



    MagicMethodContext could do:

    – security (raising exception on creation if user does not have SecurityLevel.EndUser – whatever that may be)

    – logging, when it is created and then when its destroyed at the end of the block.

    – transactions…

    But there’s one catch: when the object is destroyed at the end of the block, it can do "finally-style" cleanup, in its implementation of Dispose. But, it cannot tell if the "wrapped" code block raised an exception. If there was some way for MagicMethodContext.Dispose to tell whether or not an exception had been raised inside the "using" block, then it could do some intelligent clean up stuff – e.g. logging the exception, rolling back the transaction etc.

    Of course, doing this with attributes would be nicer, and failing that anonymous delegates may come to the rescue by letting us pass the "body" code to a wrapper routine that does the try…catch etc.

  11. Sam Wu says:

    In your MagicMethodContext, you could combine it with new StackTrace().GetFrame(1).GetMethod() to get the method of the caller. This way you can have a global definition of routines independent of any class-specific methods.

  12. Dion Almaer says:

    Damn logging. It is a flogged horse.

    AOP is all about "modularizing cross-cutting concerns". There are many of these:

    Logging & tracing

    Testing (e.g. Virtual Mock Objects)



    Session management

    Error handling

    Controller logic

    Controller invariants


    Temporal Logic


    Enforcing Policy

    In general, it is hard to go back to coding without AOP in some scenarios.

    E.g. you have a web action that needs to do some kind of work.

    Usual Code:

    deal with sessions

    handle exceptions for when to commit/rollback

    handle invarients


    AOP Modularized:

    just the business logic

    the DRY principle tells us that AOP can be of use.

    To make AOP *really* cool, the CLR should evolve like the JRockit JVM is. At the moment we find ourselves mucking around with factories all the time. This is a code smell that tells us that the language isn’t allowing us to do something. Imagine if a VM would allow you to register interceptors so when you did foo.doBar(), foo wouldn’t be a pointer that just goes and calls a method, but is a proxy itself. This would be useful for all middleware concerns.

    To get around this we use bytecode manipulation (or proxies, for a poorer mans), but we don’t have to!

    Dion Almaer

  13. Doug McClean says:

    Uses I have for a static aspect weaver:

    Security (attribute methods to indicate what permissions are required to call them, and use the attribute to guide weaving an access check with the method’s IL)

    Common parameter checks (ranges, non-nullity, length, temporal checks,…)

    Logging (admittedly) but some of the logs are for auditing or other runtime uses

    Billing for micro-services. Many method calls in my system incur a small charge against the calling users account if the results are committed. Methods are attributed with information about where in the fee schedule to look up the price, and this is used to advise the method with code to make the charge.

    Essentially, documentation and code are both generated from the same attributes (which can then be stripped from the assembly if they have no runtime value to justify their working set cost, or left in if runtime discoverability is needed).

  14. Darren Oakey says:

    For me, when I think AOP – I think three things:

    1) instrumentation. AOP would be nice for this, although I use log4net and am quite happy littering log statements around – all I really want here is to be able to get the values of parameters in a stack trace!

    2) patterns. Singleton, monospace, factory, state, strategy – how many times have we all implemented these? AOP will give these and more..

    3) extension – the MAIN reason I’d like AOP would be to be able to put all those changes into the language that I’ve always wanted. I could simulate const, I could simulate non-null, I can add methods to existing classes, in fact to every class in the system.

    However – thinking about it, while really tricky programming in aspects could give me most of what I want… What I’m really trying to achieve, and what I would much prefer is just some sort of preprocessor functionality – or more specifically something that allows me to put embed c# code in my c# code which modifies the codedom as it’s compiling – basically so I can say things like "whenever a parameter is declared, if it doesn’t have nullable<>" around the type, put "nonull<>" around the type.

    it’s funny – even though we all agreed on how bad #define was… we all used it, didn’t we? 🙂 It’s the whole domain-specific language thing.

    There’s a great book ("Generative Programming" Czarnecki/Eisenecker) that talks about code generation and intentional languages that has a lot of points I really admire…

    We have our general purpose language (c#), but we always want to build a language on top of it, which is our "rock-solid-business entity language" – or "bloody fast game language" language, and write our _actual_ code on top of that language. Code generators (like the forms designer, dataset designer or the brilliant CodeSmith) are great, but they have the following serious problems:

    1) they produce visible code

    this is a BAD thing… I always thought the great thing VB had over delphi was that when you designed a form, you didn’t get to see all the plumbing they put in – I was horrified to see VS.Net show you all that stuff… and joyous to see 2005 and partial classes trying to hide it from us again. Code Generation is only truly great when no one can touch the underlying code. Then it becomes a live thing, instead of either a once off, or a complex reverse engineering effort + high visible complexity.

    2) IDE sacrifice

    The thing is, the dataset designer and codesmith can be set to produce mostly invisible code, which is great… most of the time you ignore the behind the scenes c# file, and life is groovy.

    Trouble is, if I write code in codesmith, (which I do a lot) I completely sacrifice all the IDE help that makes VS great – suddenly I’m just in the codesmith editor – no intellisense, crap syntax highlighting etc.

    3) Large granularity

    As well, when you use some sort of code generator, you separate yourself from C#. You have to do a whole class (although partial classes gets us away from this a bit).. at once. Even with partial classes, you have to do whole methods.. There’s no way to say "whenever I put in the word DeclareSerializationContructor – generate this code" – or even better, "anything that implements ISerializable, generate this code"

    4) Context

    Finally, because the generation isn’t part of the compilation process, the code can’t take into account context. For instance, I’d like to do things like say "any caller of this function should also generate code to provide me details of the parameters they are sending me, such as their names"

    So – what it comes down to is that aspects are nice, and step us a bit of the way there, but I’d much prefer a decent code generation facility which was understood by the IDE (maybe placed markers where code would be generated, and followed intellisense through the code generation – so if the generator would produce four new methods on a class, those four methods appear in intellisense) and ran during compilation. From this, I could do literally ANYTHING I wanted, build levels of increasingly domain specific languages on top of C#, and not sacrifice _any_ performance, as highly specific code is being generated when I compile, and not sacrifice _any_ robustness, as I can generate all sorts of strongly typed validations and checks.

  15. MBA says:

    Helpful For MBA Fans.