PageRenderTime 102ms CodeModel.GetById 61ms app.highlight 3ms RepoModel.GetById 37ms app.codeStats 0ms

/src/LinFu.Proxy.Extensions/ObjectExtensions.cs

http://github.com/philiplaureano/LinFu
C# | 52 lines | 28 code | 5 blank | 19 comment | 0 complexity | 1879733d88bcb9622e1ec5c2530746fb MD5 | raw file
 1using System;
 2using LinFu.IoC;
 3using LinFu.IoC.Interfaces;
 4using LinFu.IoC.Reflection;
 5using LinFu.Proxy.Interfaces;
 6
 7namespace LinFu.Proxy
 8{
 9    /// <summary>
10    ///     A class that adds proxy support to the <see cref="object" /> class
11    /// </summary>
12    public static class ObjectExtensions
13    {
14        private static readonly IServiceContainer _container = new ServiceContainer();
15
16        static ObjectExtensions()
17        {
18            _container.LoadFromBaseDirectory("*.dll");
19        }
20
21        /// <summary>
22        ///     Creates a duck type that redirects its calls to the
23        ///     given <paramref name="target" />.
24        /// </summary>
25        /// <param name="target">The target instance that will be invoked once the duck type instance has been invoked.</param>
26        /// <param name="baseInterfaces">The additional list of interfaces that will be implemented by the duck type.</param>
27        /// <typeparam name="T">The type parameter that describes the duck type.</typeparam>
28        /// <returns>The return value from the target method.</returns>
29        public static T CreateDuck<T>(this object target, params Type[] baseInterfaces)
30        {
31            return (T) target.CreateDuck(typeof(T), baseInterfaces);
32        }
33
34        /// <summary>
35        ///     Creates a duck type that redirects its calls to the
36        ///     given <paramref name="target" />.
37        /// </summary>
38        /// <param name="target">The target instance that will be invoked once the duck type instance has been invoked.</param>
39        /// <param name="duckType">The <see cref="System.Type" /> that describes the duck type.</param>
40        /// <param name="baseInterfaces">The additional list of interfaces that will be implemented by the duck type.</param>
41        /// <returns>The return value from the target method.</returns>
42        public static object CreateDuck(this object target, Type duckType, params Type[] baseInterfaces)
43        {
44            Func<string, Type[], object[], object> implementation
45                = (methodName, typeArguments, arguments) =>
46                    target.Invoke(methodName, typeArguments, arguments);
47
48            var proxyFactory = _container.GetService<IProxyFactory>();
49            return proxyFactory.CreateProxy(duckType, implementation, baseInterfaces);
50        }
51    }
52}