main
 1using System;
 2using System.Collections.Generic;
 3using System.Linq;
 4using Castle.Core.Interceptor;
 5using Castle.DynamicProxy;
 6using gorilla.commons.infrastructure.thirdparty.castle.dynamicproxy;
 7
 8namespace gorilla.commons.infrastructure.thirdparty.Castle.DynamicProxy
 9{
10    public class CastleDynamicProxyFactory : ProxyFactory
11    {
12        readonly ProxyGenerator generator;
13
14        public CastleDynamicProxyFactory() : this(new ProxyGenerator())
15        {
16        }
17
18        public CastleDynamicProxyFactory(ProxyGenerator generator)
19        {
20            this.generator = generator;
21        }
22
23        public TypeToProxy create_proxy_for<TypeToProxy>(Func<TypeToProxy> implementation, params IInterceptor[] interceptors)
24        {
25            return create_proxy_for(lazy_load(implementation), interceptors);
26        }
27
28        T lazy_load<T>(Func<T> implementation)
29        {
30            if (typeof (T).IsInterface)
31            {
32                return generator.CreateInterfaceProxyWithoutTarget<T>(new LazyLoadedInterceptor<T>(implementation));
33            }
34            return generator.CreateClassProxy<T>(new LazyLoadedInterceptor<T>(implementation));
35        }
36
37        TypeToProxy create_proxy_for<TypeToProxy>(TypeToProxy implementation,
38                                                  IEnumerable<IInterceptor> interceptors)
39        {
40            if (typeof (TypeToProxy).IsInterface)
41            {
42                return generator.CreateInterfaceProxyWithTarget<TypeToProxy>(implementation, interceptors.ToArray());
43            }
44            var list = interceptors.ToList();
45            list.Add(new LazyLoadedInterceptor<TypeToProxy>(() => implementation));
46            return generator.CreateClassProxy<TypeToProxy>(list.ToArray());
47        }
48    }
49}