public static TInterface CreateInterfaceProxy <TInterface>(this IProxyFactory proxyGenerator)
            where TInterface : class
        {
            var type = typeof(TInterface);

            if (!type.IsInterface)
            {
                throw new InvalidOperationException($"the Type {type.FullName} is not interface");
            }
            return(proxyGenerator.CreateProxy <TInterface>());
        }
        public static TInterface CreateInterfaceProxy <TInterface, TImplement>(this IProxyFactory proxyGenerator, params object[] arguments) where TImplement : TInterface
            where TInterface : class
        {
            var type = typeof(TInterface);

            if (!type.IsInterface)
            {
                throw new InvalidOperationException($"the Type {type.FullName} is not interface");
            }
            return(proxyGenerator.CreateProxy <TInterface, TImplement>(arguments));
        }
 static object Wrap(IServiceProvider sp, Type serviceType, Type impType)
 {
     object target = sp.GetService(serviceType);
     if (target != null)
     {
         IProxyFactory proxyFactory = sp.GetRequiredService<IProxyFactory>();
         var proxyTarget = proxyFactory.CreateProxy(serviceType, target);
         target = proxyTarget ?? target;
     }
     return target;
 }
        public static TClass CreateClassProxy <TClass>(this IProxyFactory proxyGenerator) where TClass : class

        {
            var type = typeof(TClass);

            if (!type.IsClass)
            {
                throw new InvalidOperationException($"the Type {type.FullName} is not class");
            }
            return(proxyGenerator.CreateProxy <TClass>());
        }
Esempio n. 5
0
        private static object Wrap(IServiceProvider serviceProvider, Type serviceType)
        {
            object target = serviceProvider.GetService(serviceType);

            if (target != null && target is IInterceptable)
            {
                IProxyFactory proxyFactory = serviceProvider.GetRequiredService <IProxyFactory>();
                return(proxyFactory.CreateProxy(serviceType, target));
            }
            return(target);
        }
        public static TClass CreateClassProxy <TClass, TImplement>(this IProxyFactory proxyGenerator, params object[] arguments) where TImplement : TClass
            where TClass : class
        {
            var type = typeof(TClass);

            if (!type.IsClass)
            {
                throw new InvalidOperationException($"the Type {type.FullName} is not class");
            }
            return(proxyGenerator.CreateProxy <TClass, TImplement>(arguments));
        }
Esempio n. 7
0
        public ActionResult Create(ActorCreationData actor)
        {
            actor.Validate();

            if (!actor.ValidationErrors.Any())
            {
                RunAndReleaseProxy(_proxyFactory.CreateProxy <IActorService>(), proxy => proxy.Add(actor));

                TempData["Status"] = CrudNotification.Success;
                TempData["Id"]     = actor.Id;

                return(View());
            }
            else
            {
                ViewBag.ValidationErrors = actor.ValidationErrors.ToList();
                TempData["Status"]       = CrudNotification.ValidationError;
                return(View());
            }
        }
Esempio n. 8
0
        public void ShouldWrapCall()
        {
            // Given
            ITestClassWithDependency testClassWithState = TestClassWithDependency.Create();
            var proxyObject = _sutForInterface.CreateProxy(testClassWithState);

            // When
            var result = proxyObject.GetNextInt(2);

            // Then
            Assert.Equal(3, result);
        }
Esempio n. 9
0
        public static void ReferenceService <T>(ProxyOptions options, IInvokeFilter[] filters) where T : class
        {
            // 注册调用方信息
            options.ServiceKind = ServiceKind.Remote;
            options.EndpointUri = AppEnv.GlobalConfiguration.ConsumerConfiguration.Url;
            options.Attributes.Add(AttrKeys.NodeCodeConsumer, AppEnv.GlobalConfiguration.ConsumerConfiguration.NodeCode);

            IProxyFactory proxyFactory = AppEnv.GlobalConfiguration.ProxyFactory;
            var           proxy        = proxyFactory.CreateProxy <T>(options, AppEnv._invokeFilters.Concat(filters).ToArray());

            AppEnv._typeBuilder.RegisterType <T>(proxy);
        }
Esempio n. 10
0
        public Task <IEnumerable <ActiveOutageViewModel> > Handle(GetActiveOutagesQuery request, CancellationToken cancellationToken)
        {
            return(Task.Run(() =>
            {
                using (OutageAccessProxy outageProxy = _proxyFactory.CreateProxy <OutageAccessProxy, IOutageAccessContract>(EndpointNames.OutageAccessEndpoint))
                {
                    try
                    {
                        _logger.LogInfo("[OutageQueryHandler::GetActiveOutages] Sending a GET query to Outage service for active outages.");
                        IEnumerable <ActiveOutageMessage> activeOutages = outageProxy.GetActiveOutages();

                        IEnumerable <ActiveOutageViewModel> activeOutageViewModels = _mapper.MapActiveOutages(activeOutages);
                        return activeOutageViewModels;
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError("[OutageQueryHandler::GetActiveOutages] Failed to GET active outages from Outage service.", ex);
                        throw ex;
                    }
                }
            }));
        }
Esempio n. 11
0
        public static T Of <T>(IProxyFactory factory = null)
        {
            if (factory == null)
            {
                factory = ProxyFactory.Default;
            }

            var proxy = (IProxy)factory.CreateProxy(typeof(T), new[] { typeof(IMocked) }, new object[0]);

            proxy.Behaviors.Add(new MockProxyBehavior());
            proxy.Behaviors.Add(new DefaultValueProxyBehavior());

            return((T)proxy);
        }
Esempio n. 12
0
        /// <summary>
        /// Create a new <see cref="Interceptable&lt;Task&gt;"/> object.
        /// </summary>
        /// <param name="serviceProvider">The service providuer to provide injected service.</param>
        /// <exception cref="ArgumentNullException">The specified argument <paramref name="serviceProvider"/> is null.</exception>
        /// <exception cref="InvalidOperationException">The <paramref name="serviceProvider"/> cannot provide the <see cref="ProxyFactory"/>.</exception>
        public Interceptable(IServiceProvider serviceProvider)
        {
            Guard.ArgumentNotNull(serviceProvider, "serviceProvider");

            _serviceProvider = serviceProvider;
            T target = _serviceProvider.GetService <T>();

            if (null == target)
            {
                this.Proxy = null;
            }
            IProxyFactory proxyFactory = _serviceProvider.GetRequiredService <IProxyFactory>();

            this.Proxy = proxyFactory.CreateProxy <T>(target);
        }
Esempio n. 13
0
        public void CreateInstanceWithoutArguments()
        {
            var userIdProviderProxy = _proxyFactory.CreateProxy <IUserIdProvider>();

            Assert.NotNull(userIdProviderProxy);
            Assert.True(userIdProviderProxy.GetType().Namespace?.StartsWith(NamespacePrefix));

            var userIdProviderProxy2 = _proxyFactory.CreateProxy <IUserIdProvider, EnvironmentUserIdProvider>();

            Assert.NotNull(userIdProviderProxy2);
            Assert.True(userIdProviderProxy2.GetType().Namespace?.StartsWith(NamespacePrefix));

            var userId = userIdProviderProxy2.GetUserId();

            Assert.NotNull(userId);

            var eventProxy = _proxyFactory.CreateProxy <TestEvent>();

            Assert.NotNull(eventProxy);
            Assert.True(eventProxy.GetType().Namespace?.StartsWith(NamespacePrefix));
        }
Esempio n. 14
0
        /// <summary>
        /// Uses the <paramref name="proxyFactory"/> to create a proxy instance
        /// that directly derives from the <typeparamref name="T"/> type
        /// and implements the given <paramref name="baseInterfaces"/>.
        /// </summary>
        /// <remarks>
        /// The <paramref name="proxyImplementation"/> will be used to intercept method calls
        /// performed against the target instance.
        /// </remarks>
        /// <param name="targetType">The type that will be intercepted by the proxy.</param>
        /// <param name="proxyFactory">The IProxyFactory instance that will be used to generate the proxy type.</param>
        /// <param name="proxyImplementation">The functor that will invoked every time a method is called on the proxy.</param>
        /// <param name="baseInterfaces">The additional list of interfaces that the proxy will implement.</param>
        /// <returns>A valid proxy instance.</returns>
        public static object CreateProxy(this IProxyFactory proxyFactory, Type targetType,
                                         Func <string, Type[], object[], object> proxyImplementation, params Type[] baseInterfaces)
        {
            Func <IInvocationInfo, object> doIntercept = info =>
            {
                var    targetMethod  = info.TargetMethod;
                var    methodName    = targetMethod.Name;
                var    arguments     = info.Arguments;
                Type[] typeArguments = info.TypeArguments;

                return(proxyImplementation(methodName, typeArguments, arguments));
            };

            var interceptor = new FunctorAsInterceptor(doIntercept);

            return(proxyFactory.CreateProxy(targetType, interceptor, baseInterfaces));
        }
Esempio n. 15
0
        public object GetMock(Type type)
        {
            object mock;

            if (!_parameters.TryGetValue(type, out mock))
            {
                throw new InvalidOperationException();
            }

            if (mock == null)
            {
                mock = _proxyFactory.CreateProxy(type);
                _parameters[type] = mock;
            }

            return(mock);
        }
Esempio n. 16
0
        public ActionResult Create()
        {
            Role[] roles = null;

            RunAndReleaseProxy(_proxyFactory.CreateProxy <IRoleService>(),
                               proxy =>
            {
                roles = proxy.GetAll();
            });

            List <SelectListItem> rolesList = roles.Select(role => new SelectListItem()
            {
                Text  = role.Name,
                Value = role.Id.ToString()
            }).ToList();

            ViewBag.Roles = rolesList;

            return(View());
        }
Esempio n. 17
0
        public ActionResult Create(Language language)
        {
            language.Validate();

            if (!language.ValidationErrors.Any())
            {
                RunAndReleaseProxy(_proxyFactory.CreateProxy <ILanguageService>(), proxy => proxy.Update(language));

                TempData["Status"] = CrudNotification.Success;
                TempData["Id"]     = language.Id;

                return(View());
            }
            else
            {
                ViewBag.ValidationErrors = language.ValidationErrors.ToList();
                TempData["Status"]       = CrudNotification.ValidationError;
                return(View());
            }
        }
 public Task <OmsGraphViewModel> Handle(GetTopologyQuery request, CancellationToken cancellationToken)
 {
     return(Task.Run(() =>
     {
         using (UITopologyServiceProxy topologyProxy = _proxyFactory.CreateProxy <UITopologyServiceProxy, ITopologyServiceContract>(EndpointNames.TopologyServiceEndpoint))
         {
             try
             {
                 _logger.LogInfo("[TopologyQueryHandler::GetTopologyQuery] Sending GET query to topology client.");
                 UIModel topologyModel = topologyProxy.GetTopology();
                 OmsGraphViewModel graph = _mapper.Map(topologyModel);
                 return graph;
             }
             catch (Exception ex)
             {
                 _logger.LogError("[TopologyQueryHandler::GetTopologyQuery] Sending GET query to topology client failed.", ex);
                 return null;
             }
         }
     }));
 }
 public void Setup()
 {
     processor = Substitute.For<IOutgoingRequestProcessor>();
     factory = Substitute.For<IProxyFactory>();
     factory.CreateProxy<IMyService>().Returns((p, s, t) => new MyServiceProxy(p, s, t));
     container = new ProxyContainer(processor, factory);
 }
Esempio n. 20
0
 /// <summary>
 /// Uses the <paramref name="factory"/> to create a proxy instance
 /// that directly derives from the <typeparamref name="T"/> type
 /// and implements the given <paramref name="baseInterfaces"/>.
 /// The <paramref name="interceptor"/> instance, in turn, will be used
 /// to intercept the method calls made to the proxy itself.
 /// </summary>
 /// <typeparam name="T">The type that will be intercepted by the proxy.</typeparam>
 /// <param name="factory">The IProxyFactory instance that will be used to generate the proxy type.</param>
 /// <param name="interceptor">The <see cref="IInterceptor"/> instance that will be used to intercept method calls made to the proxy.</param>
 /// <param name="baseInterfaces">The additional list of interfaces that the proxy will implement.</param>
 /// <returns>A valid proxy instance.</returns>
 public static T CreateProxy <T>(this IProxyFactory factory, IInterceptor interceptor,
                                 params Type[] baseInterfaces)
 {
     return((T)factory.CreateProxy(typeof(T), interceptor, baseInterfaces));
 }
Esempio n. 21
0
 /// <summary>
 /// Uses the <paramref name="factory"/> to create a proxy instance
 /// that directly derives from the <typeparamref name="T"/> type
 /// and implements the given <paramref name="baseInterfaces"/>.
 /// The <paramref name="wrapper"/> instance, in turn, will be used
 /// to intercept the method calls made to the proxy itself.
 /// </summary>
 /// <typeparam name="T">The type that will be intercepted by the proxy.</typeparam>
 /// <param name="factory">The IProxyFactory instance that will be used to generate the proxy type.</param>
 /// <param name="wrapper">The <see cref="IInvokeWrapper"/> instance that will be used to intercept method calls made to the proxy.</param>
 /// <param name="baseInterfaces">The additional list of interfaces that the proxy will implement.</param>
 /// <returns>A valid proxy instance.</returns>
 public static T CreateProxy <T>(this IProxyFactory factory, IInvokeWrapper wrapper,
                                 params Type[] baseInterfaces)
 {
     return((T)factory.CreateProxy(typeof(T), wrapper, baseInterfaces));
 }
Esempio n. 22
0
        protected override object VisitInterception(IntercepCallSite interceptCallSite, ServiceProvider argument)
        {
            IProxyFactory proxyFactory = interceptCallSite.ProxyFactory;

            return(proxyFactory.CreateProxy(interceptCallSite.ServiceType, VisitCallSite(interceptCallSite.TargetCallSite, argument)));
        }
Esempio n. 23
0
 /// <summary>
 /// Create the specified type of proxy.
 /// </summary>
 /// <typeparam name="T">The type of proxy.</typeparam>
 /// <param name="proxyFactory">The proxy factory.</param>
 /// <param name="target">The target object wrapped by the created proxy.</param>
 /// <returns>The proxy wrapping the specified target.</returns>
 public static T CreateProxy <T>(this IProxyFactory proxyFactory, T target)
 {
     Guard.ArgumentNotNull(proxyFactory, nameof(proxyFactory));
     return((T)proxyFactory.CreateProxy(typeof(T), target));
 }
        private static IServiceCollection GetInterceptableServices(IServiceProvider serviceProvider, IServiceCollection services)
        {
            var serviceCollection = new ServiceCollection();

            foreach (var service in services)
            {
                bool isOpneGeneric = service.ServiceType.GetTypeInfo().IsGenericTypeDefinition;
                Func <IServiceProvider, object> factory = _ => Wrap(serviceProvider, service.ServiceType);
                switch (service.Lifetime)
                {
                case ServiceLifetime.Scoped:
                {
                    if (isOpneGeneric)
                    {
                        serviceCollection.AddScoped(service.ServiceType, service.ImplementationType);
                    }
                    else
                    {
                        serviceCollection.AddScoped(service.ServiceType, factory);
                    }
                    break;
                }

                case ServiceLifetime.Singleton:
                {
                    if (isOpneGeneric)
                    {
                        serviceCollection.AddSingleton(service.ServiceType, service.ImplementationType);
                    }
                    else
                    {
                        serviceCollection.AddSingleton(service.ServiceType, factory);
                    }
                    break;
                }

                case ServiceLifetime.Transient:
                {
                    if (isOpneGeneric)
                    {
                        serviceCollection.AddTransient(service.ServiceType, service.ImplementationType);
                    }
                    else
                    {
                        serviceCollection.AddTransient(service.ServiceType, factory);
                    }
                    break;
                }
                }
            }

            foreach (var group in serviceCollection.GroupBy(_ => _.ServiceType))
            {
                if (group.Count() > 1)
                {
                    serviceCollection.AddTransient(typeof(IEnumerable <>).MakeGenericType(group.Key),
                                                   _ =>
                    {
                        IProxyFactory proxyFactory = serviceProvider.GetRequiredService <IProxyFactory>();
                        var proxies = serviceProvider.GetServices(group.Key).Select(target => proxyFactory.CreateProxy(group.Key, target)).ToArray();
                        Array array = Array.CreateInstance(group.Key, proxies.Length);
                        for (int i = 0; i < group.Count(); i++)
                        {
                            array.SetValue(proxies[i], i);
                        }
                        return(array);
                    });
                }
            }
            return(serviceCollection);
        }
 public static object CreateProxy(this IProxyFactory proxyFactory, Type serviceType, params object[] arguments)
 {
     return(proxyFactory.CreateProxy(serviceType, arguments));
 }
 public static TService CreateProxy <TService>(this IProxyFactory proxyFactory) where TService : class
 {
     return((TService)proxyFactory.CreateProxy(typeof(TService)));
 }
 public static TService CreateProxy <TService, TImplement>(this IProxyFactory proxyFactory)
     where TImplement : TService
     where TService : class
 {
     return((TService)proxyFactory.CreateProxy(typeof(TService), typeof(TImplement)));
 }
Esempio n. 28
0
        public ActionResult Index()
        {
            Language[] languages = null;
            Genre[]    genres    = null;

            RunAndReleaseProxy(_proxyFactory.CreateProxy <ILanguageService>(), proxy =>
            {
                languages = proxy.GetAll();
            });

            RunAndReleaseProxy(_proxyFactory.CreateProxy <IGenreService>(), proxy =>
            {
                genres = proxy.GetAll();
            });

            ViewBag.Languages = languages;
            ViewBag.Genres    = genres;

            return(View());
        }
Esempio n. 29
0
 /// <summary>
 /// Create the interceptable proxy based on specified  target object.
 /// </summary>
 /// <typeparam name="TProxy">The return type of created interceptable proxy.</typeparam>
 /// <param name="proxyFactory">The factory to create interceptable proxy.</param>
 /// <param name="target">The target object wrapped by the created proxy.</param>
 /// <returns>The created interceptable proxy.</returns>
 /// <exception cref="ArgumentNullException">The specified <paramref name="proxyFactory"/> is null.</exception>
 public static TProxy CreateProxy <TProxy>(this IProxyFactory proxyFactory, TProxy target)
 {
     Guard.ArgumentNotNull(proxyFactory, "proxyFactory");
     return((TProxy)proxyFactory.CreateProxy(typeof(TProxy), target));
 }
 public static TService CreateProxy <TService, TImplement>(this IProxyFactory proxyFactory, params object[] arguments)
     where TImplement : TService
     where TService : class
 {
     return((TService)proxyFactory.CreateProxy(typeof(TService), typeof(TImplement), arguments));
 }
Esempio n. 31
0
 /// <summary>
 /// 根据当前参数类型和接口建立代理类
 /// </summary>
 /// <param name="proxyFactory"></param>
 /// <param name="declaringType"></param>
 /// <param name="invocationHandler"></param>
 /// <param name="arguments"></param>
 /// <returns></returns>
 public static object CreateProxy(this IProxyFactory proxyFactory, Type declaringType, IInvocationHandler invocationHandler, params object[] arguments)
 {
     return(proxyFactory.CreateProxy(declaringType, Type.EmptyTypes, invocationHandler, arguments));
 }