Search code examples
c#dependency-injectionunity-containeraopunity-interception

Unity ICallHandler vs. IInterceptionBehavior


It almost seems like Unity is providing 2 different routes to achieve AoP functionality.

The question is why? What are the differences? What would be the pros and cons of each approach?

For example using ICallHandler:

unity.Configure<Interception>()
.AddMatchingRule(
                    new TypeMatchingRule(typeof (ComplexEntity))
                ).AddMatchingRule(
                    new TypeMatchingRule(typeof (ComplexEntity.InnerEntity))
                ).AddMatchingRule(
                    new MemberNameMatchingRule("*")
                ).AddCallHandler(
                    new CallHandler()
                );

But a similar functionality can also be achieved using IInterceptionBehavior in place of ICallHandler

unity.RegisterType<ComplexEntity,ComplexEntity>
     (new VirtualMethodInterceptor(), new InterceptionBehavior)

There is also a hybrid somewhere that lets you set the interception but uses a call handler eg.

unity.Configure<Interception>()
                .SetInterceptorFor<ComplexEntity>(new VirtualMethodInterceptor())
                .AddPolicy("TestPolicy")
                .AddMatchingRule(
                    new TypeMatchingRule(typeof (ComplexEntity))
                ).AddMatchingRule(
                    new TypeMatchingRule(typeof (ComplexEntity.InnerEntity))
                ).AddMatchingRule(
                    new MemberNameMatchingRule("*")
                ).AddCallHandler(
                    new CallHandler()
                );

So which one to use? Why are there seemingly redundant solutions in a single framework?


Solution

  • Nevermind I was not looking carefully enough.

    You can create your own InterceptionBehavior, but this would only apply to the class, or you can use the library provided PolicyInjectionBehavior, which then uses ICallHandler and policies.

    So the difference ends up like a simple vs. a multi cast delegate. The policy injection allows you to define the pointcut using a container wide query (multi-cast) and apply the advice against multiple types that match the query, whereas the IInterceptionBehavior allows you to apply specific advice against specific type only (single-cast).

    The PolicyBehavior is an implementation of IInterceptionBehavior that provides the multi casting functionality.