The Need for SetInerceptorFor When Policy Already Set

Jan 9, 2009 at 1:15 AM
I'm just trying to understand these two concepts:

so i configure a Container for Interception [container.Configure<Interception>()]
then i add my Policy, say to intercept everything in an assembly [.AddMatchingRule(new AssemblyMatchingRule("MyAssembly, Version=")]
and I assign a Handler to this Policy [.AddCallHandler(new My.Extensions.MyCallHandler())]

Basically what I thought I did above was I said that I want every kind of call to every kind of member in every kind of type (public ones) in my assembly be intercepted by my call handler. Period.

Little later, trying to resolve some type or object, I get no interception.

It appears that i needed to set the interceptor, using either [.SetDefaultInterceptorFor<>] or [.SetInterceptorFor<>] , to one of Proxy, Interface, or Virtual method interceptors. However, in doing so I would have to specify the type that is to be intercepted. (may be i'm missing something somewhere else?)

But I thought i did specify, in the first part, that I wanted every type to be intercepted. Why do I have to re-specify the types to be proxied? Can I set a blanket interceptor, say for a policy?

Jan 9, 2009 at 8:26 AM
Hi, you don't have to re-specify the types.  This code works...  (IProjectsService and ProjectsService are defined in a classlibrary project "Models")  The Log method gets intercepted.

IUnityContainer container = new UnityContainer();
IProjectsService, ProjectsService>();
IProjectsService>(new InterfaceInterceptor())
typeof(AssemblyMatchingRule), new InjectionConstructor("Models"))
new LogCallHandler());
IProjectsService service = container.Resolve<IProjectsService>() as IProjectsService;


Sarah  Urmeneta
Global Technology & Solutions
Avanade, Inc.



Jan 9, 2009 at 11:06 AM
But you did specify it again: .SetDefaultInterceptorFor<IProjectsService>(new InterfaceInterceptor())
What i'm trying to say is I am telling the Container what sort of types I am interested in intercepting. Why do I have to then set the Interceptor for a very specific type?
Basically, I want to say to intercept anything on this planet, anything that I would ask the Container to Resolve later, by way of specifying MatchingRules? Isn't what a MatchingRule made for? Now for all these types that Match my Rule, I want to specify a Handler (no problem) and an Interceptor (here comes the problem).

I actually have the same problem with injection for which I will open up another discussion item.
Jan 9, 2009 at 7:13 PM
There are three parts to the interception system that all have to be configured.

First - what methods are going to be intercepted. This is what the matching rules do.
Second - what happens when those methods are intercepted. This is what the call handlers do.

The third part is a little trickier. This is HOW do the methods get intercepted?

We have three different ways to implement interception - implement the how. All three have different performance characteristics, and require different things from the class that is being intercepted. And the HOW is on a class level, not an individual method level.

One interceptor can intercept any method, but requires that you inherit from MarshalByRefObject. One of them can intercept virtual methods only, and can only connect interception at creation time. The last one can intercept only interface methods, but can be done after object creation.

There's no way that I can see to somehow go from "intercept this method" (the matching rule) to "use this interception implementation" automatically.

So, we could try to attach an interceptor implementation to a policy. But then what happens when two policies, both of which apply to some set of methods on a type, specify different interception mechanisms?

I realize it's annoying, and I'd love to hear suggestions that can simplify this. I don't see anything right now that will do that and preserve our flexibility, but I'd love to be proven wrong.

Jan 10, 2009 at 1:07 AM
Edited Jan 11, 2009 at 2:23 PM
i don't know since i never had to design a AOP module on my own. But here are a few more thoughts around this whole issue:
- As is, it is very much possible to specify an Interceptor that cannot intercept what the Policy requires. For instance, method signatures that are not "virtual" but a VirtualMethod interceptor registered for the class.
- Unless a finegrained level of control is needed, could we not have one interceptor set globally? One that you would recommend?
- Or could we not setup a list of interceptors, possibly in the order of preference, that are used by the smarts in the system when they're needed. The logic could look at the registered policies and determine which one is best in each case.
- and the point i tried to make in my other post "A Wider way of ..." which talks about rules about specifying classes not by their individual types but rather by expressions, rules, or policies if you will (may be different kinds of policies than the ones used to group methods)
Jan 10, 2009 at 9:28 PM
This is a big deal for me too. In fact, I am still using a container extension to wrap everything with PIAB 3.1 for a logging call handler. My container extension checks the object being built to see if it is MarshallByRef and then checks for an interface. If neither is supported, the object isn't wrapped.

I see your point about having fine-grained control on how to intercept, but _requiring_ it is too restrictive and undermines what AOP is all about IMO. We should have a rule-based way to apply an interceptor (or interceptor selector policy) if that's what we want to do. I know there are trade-offs, but give us opportunity to make the choice.
Jan 12, 2009 at 7:41 AM
Folks, we're in the planning phase for the next version. Feel free to post ideas about what you'd like to see in the interception API and behavior. I understand the pain around what we've currently got. No more need for "this sucks." How would you make it better?

Jan 13, 2009 at 6:08 PM
Edited Jan 13, 2009 at 7:14 PM
This is like a few other chains :

Essentially I think everyone is just looking for what the basic PolicyInjection .Create or .Wrap provide, a quick way to apply the pre defined matching policies and injections to a given class or when creating a class.  

I could be wrong but I don't think we every needed to specify the type of injection the PIAB was using in a simple case, simply setup a matching rule, handler, and .Create or Wrap.

So in my situation, we had a PIAB matching rule setup to check if the class was in our contract library.  Then in the instanceprovider in WCF we resolve the class in unity, then apply the PIAB wrapper using that configuration matching rule. 

The problem is obviously the unity daisy chaining of depedencies.  Our services typically take in depedencies like the data layer.  These auto injected dependencies are not wrapped since Unity is auto resolving/injecting.  

That was my big hope for having the PIAB integrated with Unity, so we could properly rely on the auto injection and PIAB wrapping capabilities in unity.  

As mentioned I could specify the injection approach manually as discussed, but in an enterprise application I don't want to have to specify the injection rules 100's of times for a huge enterprise project in my bootstrap config of the Unity container.
Jan 13, 2009 at 7:58 PM
You didn't need to specify what interceptor to use with PIAB because you didn't have a choice - there was (and still is) only one. Also, you didn't run an object through PIAB unless you knew that you wanted that specific object intercepted.

With Unity, these two things change. There are now three different interceptors, which means that some things that could not have been intercepted in the past now can be, and the interception can be a lot faster, but which one do we use for each object / type? Also, since building up with Unity means we're not building just one object, but an entire object graph, do you want to get interception on every single object inside that object graph, or just on specific ones? And which interception mechanism do we use on those inner objects?

The fear we had while developing this feature was that we would accidentally get interception (and possible build errors) when it wasn't wanted. So we erred on the side of explicitness - you need to specify in configuration specifically which types to intercept, and what mechanism to use.

I personally don't see a heuristic that would allow automatic selection of interception mechanism that would also satisfy everybody.

That's where I'd like you folks in the community to step in. Give me examples - how would you ideally want this to work? If we start getting explicit ideas out into the open, we can talk through the interactions and implications, and make something better.

Jan 14, 2009 at 12:07 AM
All of your concerns are very valid, and everything you have done is great, but this is just a requirement that would make life alot easier in some situations.

For example, I just want to wrap all my service instances in my exception block and logging block, this is where the ability to specify one of the interception types to all classes in my service library using a namespace match is beneficial. 

I have many developers working on many services, and don't want to have to ensure all of them properly setup the interception when items adding them to the unity container.  I also can easily know the impact of my match pattern instead of looking at a container's registration when there could be thousands.  Also, if I wanted to refactor out some base functionality, and quickly apply the exception block only to the services that extend some new interface, I would manually have to change all interceptions currently instead of changing some matching approach.

Does this make sense?  Of course we could manually set the interception per service, but it is tedious and a automatic selection of interception based on a matching pattern would be very handy.

Jan 14, 2009 at 2:01 AM
I think you misunderstand me. I don't need to be sold on the need for a change here. To be honest, I wasn't thrilled with what we have when I shipped it. But inspiration was not striking, so it was better to ship the suboptimal than not ship anything at all.

I'm asking you and the rest of the community to help design the updated feature. What specifically would you like to see? How, exactly, does it work? Can you give me a unit test that illustrates what you'd like the API and behavior to look like? That sort of thing.

And, being the person that I am, I will attempt to poke holes in every idea posted (including mine). It's not personal, it's just how I learn.

So, you want a "matching approach". Sounds like a reasonable direction to investigate. Now, can you be more specific? How exactly would that work? What's the API? What's the interaction with other uses of the container? What happens if multiple rules specifying different interceptors match?

Jan 14, 2009 at 2:26 PM
Poke away!  It's what leads to the best solution!

I was actually starting to try something out with some tests and some crude matching methods but work calls atm :(  I will do my best to get something together as soon as I can breathe.  At the very least I can try to throw a few user stories together setting up the context and expectations for the matching policies. 

You mentioned various issues that would need to be resolved to do this properly:

1.  If there was a way to say Container.SetInterceptionUsing(NameSpaceMatchingPolicy), thats well and good, but like you said, what about the interception type, should we use a global one or specific ones.  If so, which takes precedence? 

2.  What is the impact of this on other features like child containers? 

For my purposes I have always tried to limit using containers for too much conceptual logic, e.g. child containers.  So from my perspective adding this matching approach wouldn't be overly complex but everyone needs to get involved to decide how best to handle it in these other situations.

More to come when I can put something concrete together.

Jan 23, 2009 at 6:50 PM
Using the Context.Registering event, I was able to make a container extension to basically do the same thing I was doing with EntLib 3.1 which is wrap everything built up by the container (and then apply a logging call handler to it). I think it would be pretty easy to extend this with an "AssemblyMatchingInteceptorSelector : IIterceptorSelectorPolicy " or whatever. For now, my need is pretty simple and I think this will do the trick!

public class InterceptOnRegisterContainerExtension : UnityContainerExtension
    protected override void Initialize()

        Context.Registering += new EventHandler<RegisterEventArgs>(
            delegate(object sender, RegisterEventArgs e)

        Context.RegisteringInstance += new EventHandler<RegisterInstanceEventArgs>(
            delegate(object sender, RegisterInstanceEventArgs e)

    private void SetInterceptorFor(Type typeToIntercept)
        var interceptor = SelectInterceptorFor(typeToIntercept);

        if (interceptor != null)
            Container.Configure<Interception>().SetInterceptorFor(typeToIntercept, interceptor);

    private IInstanceInterceptor SelectInterceptorFor(Type typeToIntercept)
        if (typeToIntercept.IsMarshalByRef)
            return new TransparentProxyInterceptor();
        else if (typeToIntercept.IsInterface)
            return new InterfaceInterceptor();

        return null;

Jan 28, 2009 at 2:39 AM

In case, anyone's still interested in investing in the interception improvements (beyond one single Global interceptor as mentioned somewhere above) I had some thoughts which may address the following concern. I haven't looked at the source code for Unity to see what it does today but i'm guessing that the sequence of actions that i'm about to explain could eliminate this dilema:
      "There's no way that I can see to somehow go from "intercept this method" (the matching rule) to "use this interception implementation" automatically."

By following this order we may be able to come up with Interceptors selected specifically for their matching rules:
  1. specify matching rules, handlers, along with desired interceptor
  2. use the above rules to search and find elligible types
  3. for each type found, create an interceptor using the specified interceptor and the handler logic
  4. register the above type.

The above is done at the time of initialization of the container.
Once done, a resolve action for the intercepted type should return the appropriate interceptor. (without the need to additionally call .SetDefaultInterceptorFor<>)

Step 2 may have performance indications if the criteria is too wide. Too bad for us as users of Unity. It is the user's responsibility to ensure the search is narrowed down by assembly and/or namespace in addition to whatever the matching rule is.
On the Step 4, an additional benefit is that you will get notified of all problems upfront at the start of your application. Since that is the time that the registration of all interceptors/handlers take place. You don't have to wait until some hidden logic resulting in a (mis)interception get triggered (see the note regarding the potential conflict between the Interceptor and the Matching rules).

In step 3, you may encounter the issue of conflicting interceptors. For instance, a matching rule+interceptor could result in a type which is to be intecepted by a different interceptor. Establishing some global rules could eliminate this. For instance, if a type is already registered for one type of Interceptor re-registering it (implicitly) while trying to satisfy another matching rule is an error. An exception is throwng and the developer will go about fixing the rules (again at the time of container startup or as soon as you start adding matching policies)

I hope I didn't get too excited too soon.