how to intercept a specific method without using config

Jan 25, 2012 at 8:03 AM

is there a way to use code to configure (method) interception over a specific method without using config?

like to have sample as well.

Jan 26, 2012 at 6:18 AM

See Registering Policy Injection Components for info about runtime interception and policy injection.

A sample based on that would look like:

    public class MyCallHandler : ICallHandler
    {
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            Console.WriteLine("Intercept!");
            return getNext()(input, getNext);
        }

        public int Order
        {
            get
            {
                return 0;
            }
            set
            {
            }
        }
    }

    public class InterceptedType : MarshalByRefObject
    {
        public void Test()
        {
            Console.WriteLine("test");
        }

        public void MethodX()
        {
            Console.WriteLine("MethodX");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var container = new UnityContainer();
            container
                .AddNewExtension<Interception>()
                .RegisterType<MyCallHandler>()
                // Register the type to be intercepted
                .RegisterType<InterceptedType>(
                        new Interceptor<TransparentProxyInterceptor>(),
                        new InterceptionBehavior<PolicyInjectionBehavior>())
                // Configure policies
                .Configure<Interception>()
                    .AddPolicy("policy")
                        .AddCallHandler(new MyCallHandler())
                        .AddMatchingRule(new MemberNameMatchingRule("MethodX"));

            var obj = container.Resolve<InterceptedType>();
            obj.Test();
            obj.MethodX();
        }
    }

MethodX() will get intercepted but Test() will not have interception performed.

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

Jan 26, 2012 at 7:00 AM

If you declare the method you want to intercept virtual and use the VirtualMethodInterceptor or declare an interface for InterceptedType and use InterfaceInterceptor your classes won't have to inhert from MarshalByRefObject.