Click here to Skip to main content
13,863,682 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

13.9K views
14 bookmarked
Posted 14 Aug 2016
Licenced CPOL

Yet Another Aspect-Oriented Programming Framework for .NET

, 14 Aug 2016
Rate this:
Please Sign up or sign in to vote.
Shows an introduction to a new AOP framework for .NET - AspectInjector

Introduction

There are cases when aspect-oriented programming is very helpful — for example, logging, auditing, security, etc. Though .NET platform doesn't have relevant instruments out-of-the-box, there are some third-party solutions providing such capability: PostSharp, Unity, Spring .NET, Castle Windsor, Aspect .NET... And that is not the full list. However, when choosing an AOP framework for a particular task, it is worth thinking about the mechanisms implementing the injection of crosscutting functionality, about their pros and cons. Generally speaking, two approaches can be identified:

  • Compile-time injection (PostSharp)
  • Proxy-class generation at run-time (Unity, Spring .NET, Castle Windsor)

Compile-time injection is the most favorable option, because it requires no additional computational overhead during program execution, which is especially important for mobile devices. Though usual proxy-class generation has simpler implementation, apart from computational overhead, it also has some limitations — methods and properties must belong to an interface or be virtual in order to be intercepted via a proxy-class.

PostSharp offers great capabilities for aspect-oriented programming, but it is a commercial product, so may be not acceptable for some projects. As an alternative, we have developed and are continuing to improve AspectInjector — a framework, which allows applying aspects during compile-time and has simple but flexible interface.

Using the Code

Let's take a quick look at what AspectInjector can easily do. You can add the library to your project using the following command in the Package Manager console:

Install-Package AspectInjector -Pre

Currently only pre-release versions have full feature set, so "-Pre" switch is needed to get the most complete capabilities of the Aspect Injector.

Imagine we need a simple trace for all methods — just capture method start and finish. In order to accomplish this, you will need to define an aspect implementing the desired behavior:

public class TraceAspect
{
    [Advice(InjectionPoints.Before, InjectionTargets.Method)]
    public void TraceStart([AdviceArgument(AdviceArgumentSource.Type)] Type type,
        [AdviceArgument(AdviceArgumentSource.Name)] string name)
    {
        Console.WriteLine("[{0}] Method {1}.{2} started", DateTime.UtcNow, type.Name, name);
    }

    [Advice(InjectionPoints.After, InjectionTargets.Method)]
    public void TraceFinish([AdviceArgument(AdviceArgumentSource.Type)] Type type,
        [AdviceArgument(AdviceArgumentSource.Name)] string name)
    {
        Console.WriteLine("[{0}] Method {1}.{2} finished", DateTime.UtcNow, type.Name, name);
    }
}

This definition means that methods TraceStart and TraceFinish will be called at the beginning and at the end of each method correspondingly, and each call will have the information about target method’s name and its declaring type.

In order to apply the aspect to any class which needs it, just mark the target class with Aspect attribute:

[Aspect(typeof(TraceAspect))]
public class SampleClass
{
    public void Method1()
    {
    //...
    }

    public int Method2()
    {
    //...
    }
}

As the result, calls to TraceStart and TraceFinish will be injected to all methods of SampleClass. Here is the decompiled resulting code:

public class SampleClass
{
    //Added by AspectInjector
    private TraceAspect __a$i_TraceAspect;

    public void Method1()
    {
        //Added by AspectInjector
        this.__a$i_TraceAspect.TraceStart(typeof(SampleClass), "Method1");

        Console.WriteLine("Inside Method1");

        //Added by AspectInjector
        this.__a$i_TraceAspect.TraceFinish(typeof(SampleClass), "Method1");
    }

    public int Method2()
    {
        //Added by AspectInjector
        this.__a$i_TraceAspect.TraceStart(typeof(SampleClass), "Method2");

        Console.WriteLine("Inside Method2");

        //Added by AspectInjector
        int num = 1;
        int result = num;
        this.__a$i_TraceAspect.TraceFinish(typeof(SampleClass), "Method2");
        return result;
    }

    public SampleClass()
    {
        //Added by AspectInjector
        this.__a$_initializeInstanceAspects();
    }

    //Added by AspectInjector
    private void __a$_initializeInstanceAspects()
    {
        if (this.__a$i_TraceAspect == null)
        {
            this.__a$i_TraceAspect = new TraceAspect();
        }
    }
}

It was one of the simplest examples, which doesn’t show all capabilities of AspectInjector. There are more options on injection targets, target members filtering (controlled by additional parameters on Aspect attribute) and advice parameter sources. All this information can be found in the documentation.

There are some features, which deserve special attention — for example, "Around" injection point. It is currently available only in pre-release version of Aspect Injector and allows to fully wrap any calls. One of the simplest examples here is tracing call durations:

public class DurationAspect
{
    [Advice(InjectionPoints.Around, InjectionTargets.Method)]
    public object TraceDuration([AdviceArgument(AdviceArgumentSource.Type)] Type type,
        [AdviceArgument(AdviceArgumentSource.Name)] string name,
        [AdviceArgument(AdviceArgumentSource.Target)] Func<object[], object> target,
        [AdviceArgument(AdviceArgumentSource.Arguments)] object[] arguments)
    {
        var sw = new Stopwatch();
        sw.Start();

        var result = target(arguments);

        sw.Stop();
        Console.WriteLine("[{0}] Method {1}.{2} took {3} ms",
                          DateTime.UtcNow, type.Name, name, sw.ElapsedMilliseconds);

        return result;
    }
}

The main idea is that advices with InjectionPoints.Around must accept function delegate and corresponding parameters — all necessary information to make the original call. Advice method can do any extra work before and after calling the original method like shown in the example. However, "around" injection is heavier than "before" and "after" in terms of code changes. Whilst the last two modify the body of the original method, "around" creates additional wrapping functions, so it is recommended to use it only in case there is some data to be passed between start and end of a method.

One more important feature is interface injection. You may need to inject not only extra code to some methods, properties or events, but also extra interfaces to a class. A classic example here is INotifyPropertyChanged for .NET UI frameworks:

[AdviceInterfaceProxy(typeof(INotifyPropertyChanged))]
public class NotifyPropertyChangedAspect : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };

    [Advice(InjectionPoints.After, InjectionTargets.Setter)]
    public void RaisePropertyChanged(
        [AdviceArgument(AdviceArgumentSource.Instance)] object targetInstance,
        [AdviceArgument(AdviceArgumentSource.Name)] string propertyName)
    {
        PropertyChanged(targetInstance, new PropertyChangedEventArgs(propertyName));
    }
}

After that, you will have to decorate all view model classes with [Aspect(typeof(NotifyPropertyChangedAspect))] attribute, and all their properties will be automatically made notifiable.

You can find more details about available attributes and parameters on the project page. We would appreciate any feedback and suggestions for AspectInjector!

History

  • 16th August, 2016: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Yuriy I
Ukraine Ukraine
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionNeed help Pin
linh lo21-Nov-16 20:52
memberlinh lo21-Nov-16 20:52 
AnswerRe: Need help Pin
Yuriy I23-Nov-16 10:08
memberYuriy I23-Nov-16 10:08 
QuestionMy vote of 5 Pin
Shabbazz13-Oct-16 17:51
professionalShabbazz13-Oct-16 17:51 
AnswerRe: My vote of 5 Pin
Yuriy I22-Oct-16 11:57
memberYuriy I22-Oct-16 11:57 
GeneralRe: My vote of 5 Pin
Shabbazz25-Oct-16 17:56
professionalShabbazz25-Oct-16 17:56 
QuestionException handling Pin
Jesper Krejberg Petersen17-Aug-16 11:58
memberJesper Krejberg Petersen17-Aug-16 11:58 
AnswerRe: Exception handling Pin
Yuriy I18-Aug-16 11:07
memberYuriy I18-Aug-16 11:07 
GeneralRe: Exception handling Pin
Jesper Krejberg Petersen18-Aug-16 20:29
memberJesper Krejberg Petersen18-Aug-16 20:29 
GeneralMy vote of 4 Pin
Dr. Jones DK17-Aug-16 3:49
professionalDr. Jones DK17-Aug-16 3:49 
GeneralMy vote of 5 Pin
Ravi Shankar K16-Aug-16 21:43
memberRavi Shankar K16-Aug-16 21:43 
QuestionWTF is an AOP? Pin
W. Kleinschmit16-Aug-16 7:41
memberW. Kleinschmit16-Aug-16 7:41 
AnswerRe: WTF is an AOP? Pin
Yuriy I16-Aug-16 11:10
memberYuriy I16-Aug-16 11:10 
Question+1 Pin
SergeyAB15-Aug-16 23:20
memberSergeyAB15-Aug-16 23:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190214.1 | Last Updated 15 Aug 2016
Article Copyright 2016 by Yuriy I
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid