public static void Invoke_Receives_Correct_Arguments()
        {
            object[] actualArgs = null;

            TestType_IHelloService proxy = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                actualArgs = args;
                return(String.Empty);
            };

            proxy.Hello("testInput");

            object[] expectedArgs = new object[] { "testInput" };
            Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length,
                        String.Format("Invoked expected object[] of length {0} but actual was {1}",
                                      expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString())));
            for (int i = 0; i < expectedArgs.Length; ++i)
            {
                Assert.True(expectedArgs[i].Equals(actualArgs[i]),
                            String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
                                          i, expectedArgs[i], actualArgs[i]));
            }
        }
        public static void Proxy_Declares_Interface_Properties()
        {
            TestType_IPropertyService proxy = DispatchProxyAsync.Create <TestType_IPropertyService, TestDispatchProxyAsync>();
            PropertyInfo propertyInfo       = proxy.GetType().GetTypeInfo().GetDeclaredProperty("ReadWrite");

            Assert.NotNull(propertyInfo);
        }
        public static void Create_Proxy_Derives_From_DispatchProxyAsync_BaseType()
        {
            TestType_IHelloService proxy = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();

            Assert.NotNull(proxy);
            Assert.IsAssignableFrom <TestDispatchProxyAsync>(proxy);
        }
        public static void Proxy_Declares_Interface_Events()
        {
            TestType_IEventService proxy = DispatchProxyAsync.Create <TestType_IEventService, TestDispatchProxyAsync>();
            EventInfo eventInfo          = proxy.GetType().GetTypeInfo().GetDeclaredEvent("AddRemove");

            Assert.NotNull(eventInfo);
        }
        public static void Proxy_Declares_Interface_Indexers()
        {
            TestType_IIndexerService proxy        = DispatchProxyAsync.Create <TestType_IIndexerService, TestDispatchProxyAsync>();
            PropertyInfo             propertyInfo = proxy.GetType().GetTypeInfo().GetDeclaredProperty("Item");

            Assert.NotNull(propertyInfo);
        }
        public static void Invoke_Indexer_Setter_And_Getter_Invokes_Correct_Methods()
        {
            List <MethodInfo> invokedMethods = new List <MethodInfo>();

            TestType_IIndexerService proxy = DispatchProxyAsync.Create <TestType_IIndexerService, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                invokedMethods.Add(method);
                return(null);
            };


            proxy["key"] = "testValue";
            string actualValue = proxy["key"];

            Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count));

            PropertyInfo propertyInfo = typeof(TestType_IIndexerService).GetTypeInfo().GetDeclaredProperty("Item");

            Assert.NotNull(propertyInfo);

            MethodInfo expectedMethod = propertyInfo.SetMethod;

            Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been {0} but actual was {1}",
                                                                                                        expectedMethod.Name, invokedMethods[0]));

            expectedMethod = propertyInfo.GetMethod;
            Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been {0} but actual was {1}",
                                                                                                        expectedMethod.Name, invokedMethods[1]));

            Assert.Null(actualValue);
        }
示例#7
0
        internal static TProxy CreateProxy <TProxy>(IServiceProvider container) where TProxy : IApiContract
        {
            object proxy = DispatchProxyAsync.Create <TProxy, HttpDispatchProxy>();
            var    proxyContextFilter = container.GetRequiredService <IProxyContextFilter>();
            var    proxyContext       = new ProxyContext(typeof(TProxy));

            var cultureFactory = container.GetService <ICultureFactory>();

            if (cultureFactory != null)
            {
                proxyContext.CultureFactory = cultureFactory.Invoke;
            }

            proxyContextFilter.Invoke(proxyContext);

            var initializer = proxy.GetType().GetMethod(nameof(HttpDispatchProxy.Initialize));

            if (initializer == null)
            {
                throw new ArgumentNullException(nameof(initializer));
            }

            initializer.Invoke(proxy, new[] { proxyContext, (object)container.GetService <IProxyManager>() });
            return((TProxy)proxy);
        }
示例#8
0
        public static TProxy CreateProxy <TProxy>(IServiceProvider container) where TProxy : IApiContract
        {
            dynamic proxy          = DispatchProxyAsync.Create <TProxy, HttpDispatchProxy>();
            var     contextAcessor = container.GetService <IHttpContextAccessor>();

            if (contextAcessor?.HttpContext == null)
            {
                return(default(TProxy));
            }

            var context = new ProxyContext(typeof(TProxy));

            if (contextAcessor?.HttpContext.Request != null)
            {
                context.ClientIp  = contextAcessor.HttpContext.GetIp();
                context.UserAgent = contextAcessor.HttpContext.Request.GetUserAgent();
                if (contextAcessor.HttpContext.Request.QueryString.HasValue)
                {
                    context.QueryString = contextAcessor.HttpContext.Request.QueryString.Value;
                }
            }

            proxy.Initialize(context, container.GetService <IProxyManager>());
            return(proxy);
        }
        public static void Invoke_Multiple_Parameters_Receives_Correct_Arguments()
        {
            object[] invokedArgs  = null;
            object[] expectedArgs = new object[] { (int)42, "testString", (double)5.0 };

            TestType_IMultipleParameterService proxy = DispatchProxyAsync.Create <TestType_IMultipleParameterService, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                invokedArgs = args;
                return(0.0);
            };

            proxy.TestMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]);

            Assert.True(invokedArgs != null && invokedArgs.Length == expectedArgs.Length,
                        String.Format("Expected {0} arguments but actual was {1}",
                                      expectedArgs.Length, invokedArgs == null ? "null" : invokedArgs.Length.ToString()));

            for (int i = 0; i < expectedArgs.Length; ++i)
            {
                Assert.True(expectedArgs[i].Equals(invokedArgs[i]),
                            String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
                                          i, expectedArgs[i], invokedArgs[i]));
            }
        }
        public static void Invoke_Multiple_Parameters_Via_Params_Receives_Correct_Arguments()
        {
            object[] actualArgs   = null;
            object[] invokedArgs  = null;
            object[] expectedArgs = new object[] { 42, "testString", 5.0 };

            TestType_IMultipleParameterService proxy = DispatchProxyAsync.Create <TestType_IMultipleParameterService, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                invokedArgs = args;
                return(String.Empty);
            };

            proxy.ParamsMethod((int)expectedArgs[0], (string)expectedArgs[1], (double)expectedArgs[2]);

            // All separate params should have become a single object[1] array
            Assert.True(invokedArgs != null && invokedArgs.Length == 1,
                        String.Format("Expected single element object[] but actual was {0}",
                                      invokedArgs == null ? "null" : invokedArgs.Length.ToString()));

            // That object[1] should contain an object[3] containing the args
            actualArgs = invokedArgs[0] as object[];
            Assert.True(actualArgs != null && actualArgs.Length == expectedArgs.Length,
                        String.Format("Invoked expected object[] of length {0} but actual was {1}",
                                      expectedArgs.Length, (actualArgs == null ? "null" : actualArgs.Length.ToString())));
            for (int i = 0; i < expectedArgs.Length; ++i)
            {
                Assert.True(expectedArgs[i].Equals(actualArgs[i]),
                            String.Format("Expected arg[{0}] = '{1}' but actual was '{2}'",
                                          i, expectedArgs[i], actualArgs[i]));
            }
        }
        public static void Create_Same_Proxy_Type_And_Base_Type_Reuses_Same_Generated_Type()
        {
            TestType_IHelloService proxy1 = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();
            TestType_IHelloService proxy2 = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();

            Assert.NotNull(proxy1);
            Assert.NotNull(proxy2);
            Assert.IsType(proxy1.GetType(), proxy2);
        }
        public static void Created_Proxy_With_Different_Proxy_Type_Use_Different_Generated_Type()
        {
            TestType_IHelloService   proxy1 = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();
            TestType_IGoodbyeService proxy2 = DispatchProxyAsync.Create <TestType_IGoodbyeService, TestDispatchProxyAsync>();

            Assert.NotNull(proxy1);
            Assert.NotNull(proxy2);
            Assert.False(proxy1.GetType() == proxy2.GetType(),
                         String.Format("Proxy generated for type {0} used same for type {1}", typeof(TestType_IHelloService).Name, typeof(TestType_IGoodbyeService).Name));
        }
        public static void Create_Proxy_Instances_Of_Same_Proxy_And_Base_Type_Are_Unique()
        {
            TestType_IHelloService proxy1 = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();
            TestType_IHelloService proxy2 = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();

            Assert.NotNull(proxy1);
            Assert.NotNull(proxy2);
            Assert.False(object.ReferenceEquals(proxy1, proxy2),
                         String.Format("First and second instance of proxy type {0} were the same instance", proxy1.GetType().Name));
        }
        public static void Create_Proxy_Implements_All_Interfaces()
        {
            TestType_IHelloAndGoodbyeService proxy = DispatchProxyAsync.Create <TestType_IHelloAndGoodbyeService, TestDispatchProxyAsync>();

            Assert.NotNull(proxy);
            Type[] implementedInterfaces = typeof(TestType_IHelloAndGoodbyeService).GetTypeInfo().ImplementedInterfaces.ToArray();
            foreach (Type t in implementedInterfaces)
            {
                Assert.IsAssignableFrom(t, proxy);
            }
        }
        public static void Invoke_Returns_Correct_Value()
        {
            TestType_IHelloService proxy = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                return("testReturn");
            };

            string expectedResult = "testReturn";
            string actualResult   = proxy.Hello(expectedResult);

            Assert.Equal(expectedResult, actualResult);
        }
        static void testGenericMethodRoundTrip <T>(T testValue)
        {
            var proxy = DispatchProxyAsync.Create <TypeType_GenericMethod, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (mi, a) =>
            {
                Assert.True(mi.IsGenericMethod);
                Assert.False(mi.IsGenericMethodDefinition);
                Assert.Equal(1, mi.GetParameters().Length);
                Assert.Equal(typeof(T), mi.GetParameters()[0].ParameterType);
                Assert.Equal(typeof(T), mi.ReturnType);
                return(a[0]);
            };
            Assert.Equal(proxy.Echo(testValue), testValue);
        }
        public static void Invoke_Receives_Correct_MethodInfo()
        {
            MethodInfo invokedMethod = null;

            TestType_IHelloService proxy = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                invokedMethod = method;
                return(String.Empty);
            };

            proxy.Hello("testInput");

            MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello");

            Assert.True(invokedMethod != null && expectedMethod == invokedMethod, String.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod));
        }
        public static void Invoke_Void_Returning_Method_Accepts_Null_Return()
        {
            MethodInfo invokedMethod = null;

            TestType_IOneWay proxy = DispatchProxyAsync.Create <TestType_IOneWay, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                invokedMethod = method;
                return(null);
            };

            proxy.OneWay();

            MethodInfo expectedMethod = typeof(TestType_IOneWay).GetTypeInfo().GetDeclaredMethod("OneWay");

            Assert.True(invokedMethod != null && expectedMethod == invokedMethod, String.Format("Invoke expected method {0} but actual was {1}", expectedMethod, invokedMethod));
        }
        public static void Invoke_Thrown_Exception_Rethrown_To_Caller()
        {
            Exception actualException = null;
            InvalidOperationException expectedException = new InvalidOperationException("testException");

            TestType_IHelloService proxy = DispatchProxyAsync.Create <TestType_IHelloService, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                throw expectedException;
            };

            try
            {
                proxy.Hello("testCall");
            }
            catch (Exception e)
            {
                actualException = e;
            }

            Assert.Equal(expectedException, actualException);
        }
        public static void Invoke_Same_Method_Multiple_Interfaces_Calls_Correct_Method()
        {
            List <MethodInfo> invokedMethods = new List <MethodInfo>();

            TestType_IHelloService1And2 proxy = DispatchProxyAsync.Create <TestType_IHelloService1And2, TestDispatchProxyAsync>();

            ((TestDispatchProxyAsync)proxy).CallOnInvoke = (method, args) =>
            {
                invokedMethods.Add(method);
                return(null);
            };

            ((TestType_IHelloService)proxy).Hello("calling 1");
            ((TestType_IHelloService2)proxy).Hello("calling 2");

            Assert.True(invokedMethods.Count == 2, String.Format("Expected 2 method invocations but received {0}", invokedMethods.Count));

            MethodInfo expectedMethod = typeof(TestType_IHelloService).GetTypeInfo().GetDeclaredMethod("Hello");

            Assert.True(invokedMethods[0] != null && expectedMethod == invokedMethods[0], String.Format("First invoke should have been TestType_IHelloService.Hello but actual was {0}", invokedMethods[0]));

            expectedMethod = typeof(TestType_IHelloService2).GetTypeInfo().GetDeclaredMethod("Hello");
            Assert.True(invokedMethods[1] != null && expectedMethod == invokedMethods[1], String.Format("Second invoke should have been TestType_IHelloService2.Hello but actual was {0}", invokedMethods[1]));
        }
        public static TProxy CreateProxy <TProxy>(IServiceProvider container) where TProxy : IApiContract
        {
            dynamic proxy = DispatchProxyAsync.Create <TProxy, HttpDispatchProxyAsync>();

            return(proxy);
        }
 public static void Create_Using_Concrete_Proxy_Type_Throws_ArgumentException()
 {
     Assert.Throws <ArgumentException>("T", () => DispatchProxyAsync.Create <TestType_ConcreteClass, TestDispatchProxyAsync>());
 }
        public static void Create_Proxy_Implements_Internal_Interfaces()
        {
            TestType_InternalInterfaceService proxy = DispatchProxyAsync.Create <TestType_PublicInterfaceService_Implements_Internal, TestDispatchProxyAsync>();

            Assert.NotNull(proxy);
        }
 public static void Create_Using_Abstract_BaseType_Throws_ArgumentException()
 {
     Assert.Throws <ArgumentException>("TProxy", () => DispatchProxyAsync.Create <TestType_IHelloService, Abstract_TestDispatchProxyAsync>());
 }
 public static void Create_Using_BaseType_Without_Default_Ctor_Throws_ArgumentException()
 {
     Assert.Throws <ArgumentException>("TProxy", () => DispatchProxyAsync.Create <TestType_IHelloService, NoDefaultCtor_TestDispatchProxyAsync>());
 }
        public T CreateClient <T>()
        {
            var type = typeof(T);

            if (_singleObjects.TryGetValue(type, out var instance))
            {
                return((T)instance);
            }

            lock (_singleObjects)
            {
                if (_singleObjects.TryGetValue(type, out instance))
                {
                    return((T)instance);
                }
                var service = type.GetCustomAttribute <DubboServiceAttribute>();
                if (service == null)
                {
                    throw new ArgumentException($"the type {type.Name} is not a dubbo service !");
                }
                var config = new ServiceConfig()
                {
                    Host        = NetUtils.GetLocalHost(),
                    Application = ".net client",
                    Category    = "consumers",
                    Protocol    = ServiceConfig.DubboConsumer,
                    ServiceName = service.TargetService,
                    Side        = "consumer"
                };
                var methodDictionary = new Dictionary <MethodInfo, InvokeContext>(MethodEqualityComparer);
                var methods          = type.GetMethods(BindingFlags.Public | BindingFlags.Instance);
                var methodNames      = new List <string>(methods.Length);
                foreach (var methodInfo in methods)
                {
                    var dubboMethod = methodInfo.GetCustomAttribute <DubboMethodAttribute>();
                    if (dubboMethod == null)
                    {
                        continue;
                    }

                    var returnType = methodInfo.ReturnType;
                    var isAsync    = typeof(Task).IsAssignableFrom(returnType);
                    if (isAsync && returnType.IsGenericType)
                    {
                        returnType = returnType.GetGenericArguments()[0];
                    }
                    var parameterDesc = GetTypeDesc(methodInfo.GetParameters());
                    methodDictionary.Add(methodInfo, new InvokeContext
                    {
                        Service           = service.TargetService,
                        Group             = service.Group,
                        Version           = service.Version,
                        Timeout           = Math.Max(dubboMethod.Timeout, service.Timeout),
                        Method            = dubboMethod.TargetMethod,
                        ParameterTypeInfo = parameterDesc,
                        IsAsync           = isAsync,
                        ReturnType        = returnType
                    });
                    methodNames.Add(dubboMethod.TargetMethod);
                }
                config.Methods = methodNames.ToArray();

                var dubboInvoker = new DubboInvoker(new ReadOnlyDictionary <MethodInfo, InvokeContext>(methodDictionary));
                registry.Register(config).Wait();
                registry.Subscribe(config, providers =>
                {
                    dubboInvoker.RefreshConnection(providers.ToSet());
                }).Wait();
                var client = DispatchProxyAsync.Create <T, DefaultProxy>();
                var proxy  = Convert(client);
                proxy.DubboInvoker = dubboInvoker;
                _singleObjects.TryAdd(type, proxy);
                return(client);
            }
        }