Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Aspect instance management

samoshkin edited this page Oct 6, 2011 · 1 revision

Aspect instance management – is how and where aspect instances are managed? There are two options: aspects instances are created internally by SNAP or aspects are managed by your favorite DI/IoC container.

Aspects are singletons and created by internally SNAP

Consider the following SNAP configuration.

var builder = new ContainerBuilder();

SnapConfiguration.For(new AutofacAspectContainer(builder)).Configure(c =>
{
    c.IncludeNamespace("SnapTests.*");
    c.Bind<FirstInterceptor>().To<FirstAttribute>();
    c.Bind<SecondInterceptor>().To<SecondAttribute>();
});

This way, SNAP will create a single instance for FirstInterceptor and SecondInterceptor interceptor classes and use it for all interceptions of methods decorated with FirstAttribute and SecondAttribute respectively. In other words, aspect is a singleton, created internally by a SNAP.

All aspects are kept in a container

Another, more attractive option, is to let your favorite DI/IoC container manage your aspects.

var builder = new ContainerBuilder();

SnapConfiguration.For(new AutofacAspectContainer(builder)).Configure(c =>
{
    c.IncludeNamespace("SnapTests.*");
    c.Bind<FirstInterceptor>().To<FirstAttribute>();
    c.Bind<SecondInterceptor>().To<SecondAttribute>();
    c.AllAspects().KeepInContainer();
});

builder.Register(r => new FirstInterceptor("first_kept_in_container"));
builder.Register(r => new SecondInterceptor("second_kept_in_container"));

This way, whenever SNAP needs an aspect for the interception, it will use DI/IoC container to resolve the aspect instance.

Only selected aspects are kept in a container

In this scenario, only a subset of all aspects are kept in container, while other are not.

var builder = new ContainerBuilder();

SnapConfiguration.For(new AutofacAspectContainer(builder)).Configure(c =>
{
    c.IncludeNamespace("SnapTests.*");
    c.Bind<FirstInterceptor>().To<FirstAttribute>();
    c.Bind<SecondInterceptor>().To<SecondAttribute>();
    c.Aspects(typeof(FirstInterceptor)).KeepInContainer();
});

builder.Register(r => new FirstInterceptor("first_kept_in_container"));

Here, SNAP will call container to resolve FirstInterceptor aspect, and will create instance of SecondInterceptor aspect on its own.

That is it
See this blog post with an example of logging aspect implementation and detailed explanation of why is it better to keep aspects in a container rather than letting SNAP to manage them.