统一 - 用几个接口拦截类调用

时间:2012-03-22 20:51:46

标签: unity-container

我有这个代码

public interface Interfcae1
    {
        void OP1();
    }

    public interface Interfcae2
    {
        void OP2();
    }

    public interface Interfcae3
    {
        void OP3();
    }

    public class Multi : Interfcae1, Interfcae2, Interfcae3
    {
        public void OP1()
        {
            System.Threading.Thread.Sleep(500);
        }

        public void OP2()
        {
            System.Threading.Thread.Sleep(1500);
        }

        public void OP3()
        {
            System.Threading.Thread.Sleep(2500);
        }
    }

我想使用unity来拦截所有函数调用,以测试每次调用所需的时间。

我的主要代码是

IUnityContainer container = new UnityContainer();
container.AddNewExtension<Interception>();
container.RegisterType<Interfcae1, Multi>(
                        // new InjectionConstructor(typeof(string)),
                         new Interceptor<TransparentProxyInterceptor>(),
                         new InterceptionBehavior<InterceptBehavior>());
container.RegisterType<Interfcae2, Multi>(
                // new InjectionConstructor(typeof(string)),
                         new Interceptor<TransparentProxyInterceptor>(),
                         new InterceptionBehavior<InterceptBehavior>());
container.RegisterType<Interfcae2, Multi>(
                // new InjectionConstructor(typeof(string)),
                         new Interceptor<TransparentProxyInterceptor>(),
                         new InterceptionBehavior<InterceptBehavior>());

var proxy = container.Resolve<Multi>();

但是我决定异常,该类型不可拦截

1 个答案:

答案 0 :(得分:1)

你还记得Configure吗?

var intp = container.Configure<Interception>()
    .SetInterceptorFor(qualifiedType, new TransparentProxyInterceptor());

在那之后,做一个AddPolicy你应该好好去...记住指定要拦截的接口的类型信息,以及拦截处理程序。

var policy = intp.AddPolicy("myFirstInterception");
policy.AddMatchingRule<TypeMatchingRule>(
    new InjectionConstructor(
        new InjectionParameter(typeof(Interface1))))
            .AddCallHandler(typeof(MyInterceptionHandler), 
                new ContainerControlledLifetimeManager());

还尝试将Multi类定义修改为:

public class Multi : MarshalByRefObject, Interfcae1, Interfcae2, Interfcae3