Global Interception

Nov 28, 2011 at 9:40 AM

Hello, Tell me please: Can I set global interception for all interfaces which register in container?

Thank you

Nov 29, 2011 at 4:02 AM

In Unity 2.0 the interception approach is an explicit one.  You need to specify that interception is going to occur and what is to occur when the interception happens.  See Configuring a Container for Interception for more information.

What you could do to automate interception is create your own helper methods to register the interception when you register the interfaces.  Or an even more seamless/elegant approach would be to create a UnityContainerExtention to automatically set up interception and register the appropriate interceptor and behavior/handler for the registered interfaces.

A short (non-production) example would be something like:

    public class UnityInterfaceInterceptionRegisterer : UnityContainerExtension
    {
        protected override void Initialize()
        {
            base.Container.AddNewExtension<Interception>();

            base.Container.Configure<Interception>()
                .AddPolicy("MyPolicy")
                .AddMatchingRule(new AlwaysMatchRule())
                .AddCallHandler(new LogCallHandler());

            base.Context.Registering += new EventHandler<RegisterEventArgs>(this.OnRegister);
        }

        private void OnRegister(object sender, RegisterEventArgs e)
        {
            IUnityContainer container = sender as IUnityContainer;
            
            if (e != null && e.TypeFrom != null && e.TypeFrom.IsInterface)
            {
                container.Configure<Interception>().SetInterceptorFor(e.TypeFrom, e.Name, new InterfaceInterceptor());
            }
        }
    }

where LogCallHandler is a custom ICallHandler that does some pre/post call logging and AlwaysMatchRule is a custom IMatchingRule that always returns true.

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com

Nov 29, 2011 at 10:18 AM
Edited Nov 29, 2011 at 10:18 AM

Thank you very much

Nov 29, 2011 at 11:09 PM

I would also add that another benefit of a Container Extension is that it will also work with design time configuration (i.e. config file).

 

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com