main
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using Castle.Core.Interceptor;
 5using gorilla.commons.infrastructure.thirdparty.Castle.DynamicProxy.Interceptors;
 6
 7namespace gorilla.commons.infrastructure.thirdparty.Castle.DynamicProxy
 8{
 9    public class CastleDynamicProxyBuilder<TypeToProxy> : ProxyBuilder<TypeToProxy>
10    {
11        readonly IDictionary<IInterceptor, InterceptorConstraint<TypeToProxy>> constraints;
12        readonly ProxyFactory proxy_factory;
13        readonly InterceptorConstraintFactory constraint_factory;
14
15        public CastleDynamicProxyBuilder() : this(new CastleDynamicProxyFactory(), new CastleDynamicInterceptorConstraintFactory())
16        {
17        }
18
19        public CastleDynamicProxyBuilder(ProxyFactory proxy_factory, InterceptorConstraintFactory constraint_factory)
20        {
21            this.proxy_factory = proxy_factory;
22            this.constraint_factory = constraint_factory;
23            constraints = new Dictionary<IInterceptor, InterceptorConstraint<TypeToProxy>>();
24        }
25
26        public ConstraintSelector<TypeToProxy> add_interceptor<Interceptor>(Interceptor interceptor)
27            where Interceptor : IInterceptor
28        {
29            var constraint = constraint_factory.CreateFor<TypeToProxy>();
30            constraints.Add(interceptor, constraint);
31            return constraint;
32        }
33
34        public ConstraintSelector<TypeToProxy> add_interceptor<Interceptor>() where Interceptor : IInterceptor, new()
35        {
36            return add_interceptor(new Interceptor());
37        }
38
39        public TypeToProxy create_proxy_for(TypeToProxy target)
40        {
41            return create_proxy_for(() => target);
42        }
43
44        public TypeToProxy create_proxy_for(Func<TypeToProxy> target)
45        {
46            return proxy_factory.create_proxy_for(target, all_interceptors_with_their_constraints().ToArray());
47        }
48
49        IEnumerable<IInterceptor> all_interceptors_with_their_constraints()
50        {
51            foreach (var pair in constraints)
52            {
53                var constraint = pair.Value;
54                var interceptor = pair.Key;
55                if (constraint.methods_to_intercept().Count() > 0)
56                {
57                    yield return new SelectiveInterceptor(constraint.methods_to_intercept(), interceptor);
58                }
59                else
60                {
61                    yield return interceptor;
62                }
63            }
64        }
65    }
66}