protected override async Task HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext)
        {
            // Disable request body data rate for client streaming
            DisableMinRequestBodyDataRateAndMaxRequestBodySize(httpContext);

            if (_pipelineInvoker == null)
            {
                var service = (TService)ServiceActivator.Create(serverCallContext, typeof(TService));
                try
                {
                    await _invoker(
                        service,
                        new HttpContextStreamReader <TRequest>(serverCallContext, Method.RequestMarshaller.ContextualDeserializer),
                        new HttpContextStreamWriter <TResponse>(serverCallContext, Method.ResponseMarshaller.ContextualSerializer),
                        serverCallContext);
                }
                finally
                {
                    await ServiceActivator.ReleaseAsync(service);
                }
            }
            else
            {
                await _pipelineInvoker(
                    new HttpContextStreamReader <TRequest>(serverCallContext, Method.RequestMarshaller.ContextualDeserializer),
                    new HttpContextStreamWriter <TResponse>(serverCallContext, Method.ResponseMarshaller.ContextualSerializer),
                    serverCallContext);
            }
        }
 public EnrollmentRequest()
 {
     using (var serviceScope = ServiceActivator.GetScope())
     {
         _validators = serviceScope.ServiceProvider.GetServices <IValidator <EnrollmentRequest> >();
     };
 }
示例#3
0
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string action     = filterContext.ActionDescriptor.ActionName;
            string actionPath = "/" + controller + "/" + action;

            _logger.Info("菜单高亮:" + actionPath + ";访问IP:" + CerCommon.GetIp() + "; 登录账号:" + filterContext.HttpContext.User.Identity.Name);

            filterContext.Controller.ViewData["CurrentMenu"]       = CurrentItem;
            filterContext.Controller.ViewData["CurrentParentItem"] = CurrentParentItem;
            var    cache = filterContext.HttpContext.Cache;
            string key   = string.Format("rolefunction_{0}", ContextService.Current.GetCookieValue("role"));

            if (cache[key] == null)
            {
                Guid rs;
                if (!Guid.TryParse(ContextService.Current.GetCookieValue("role"), out rs))
                {
                    var user = ServiceActivator.Get <UserService>().GetByUserName(filterContext.HttpContext.User.Identity.Name);
                    rs = user.RoleId;
                    ContextService.Current.SetCookie("role", user.RoleId.ToString());
                }
                var menus = ServiceActivator.Get <RoleFunctionService>().Get(rs);
                cache.Add(key, menus, new SqlCacheDependency("MonkeyCacheDependency", "BASE_ROLEFUNCTIONS"), Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
            }
            //ContextService.Current.Cache("");

            filterContext.Controller.ViewData["Menus"] = cache[key];
            base.OnActionExecuted(filterContext);
        }
示例#4
0
        public void RemoveCachedItem(RoutedItem routedItem)
        {
            using var scope = ServiceActivator.GetScope();
            var cacheService = scope.ServiceProvider.GetRequiredService <IConnectionCacheResponseService>();

            cacheService.RemoveCachedItem(Connection, routedItem, cache);
        }
示例#5
0
        public static void AddTokenRepositoryV2(this IServiceCollection services, string server, int maxRateLimit, TimeSpan restDuration, TimeSpan watchDuration, int maxForDuration = int.MinValue, bool blocking = false)
        {
            var apiLimitsConfig = new ApiLimitsConfig();

            apiLimitsConfig.Setup(server, maxRateLimit, restDuration, watchDuration, maxForDuration, blocking);
            var sp         = services.BuildServiceProvider();
            var logFactory = sp.GetRequiredService <ILoggerFactory>();

            if (maxForDuration > 0 && maxRateLimit > 0) //injects only 2 ITokenRepository
            {
                services.AddSingleton <IGrantToken>(sevs =>
                {
                    return(new MultiTokenApiGateway(apiLimitsConfig, logFactory));
                });
            }
            else if (maxForDuration > 0 || maxRateLimit > 0) //injects only 1 ITokenRepository
            {
                services.AddSingleton <IGrantToken>(sevs =>
                {
                    return(new SingleTokenApiGateway(apiLimitsConfig, logFactory));
                });
            }
            else
            {
                throw new InvalidOperationException("ITokenRepository cannot be determined, make sure configuration is valid to inject at least 1 ITokenRepository.");
            }

            ServiceActivator.Configure(sp);//Only for using Fody Attributes
        }
示例#6
0
        protected override void DoExecute(ExecutionEvent executionEvent)
        {
            IPresetCRUDService presetCRUDService = ServiceActivator.Get <IPresetCRUDService>();

            presetCRUDService.SetAsDefault(executionEvent.GetFirstSelectedTreeNavigationItem().Id, executionEvent.GetMasterTreeNavigationItem().Id);
            OnSuccessful(executionEvent, IdConstants.PRESET_FOLDER_ID);
        }
示例#7
0
 public async Task SendToRules(int taskID, bool responsive = true)
 {
     using var scope = ServiceActivator.GetScope();
     var adapter = scope.ServiceProvider.GetRequiredService <IConnectionToRulesManagerAdapter>();
     var args    = new ConnectionToRulesManagerAdapterArgs(Connection, toRules, cache, this);
     await adapter.SendToRules(taskID, args, responsive);
 }
        /// <summary>
        /// Instantiates the given class.
        /// </summary>
        /// <param name="self">The injector itself.</param>
        /// <param name="class">The class to be instantiated.</param>
        /// <param name="explicitArgs">The explicit arguments (in the form of [parameter name - parameter value]). Explicit arguments won't be resolved by the injector.</param>
        /// <returns>The new instance.</returns>
        /// <remarks>
        /// <list type="bullet">
        /// <item><description>The <paramref name="class"/> you passed must have only one public constructor or you must annotate the appropriate one with the <see cref="ServiceActivatorAttribute"/>.</description></item>
        /// <item><description>Constructor parameteres that are not present in the <paramref name="explicitArgs"/> are treated as a normal dependency.</description></item>
        /// <item><description>The caller is responsible for freeing the returned instance.</description></item>
        /// </list>
        /// </remarks>
        /// <exception cref="ServiceNotFoundException">One or more dependecies could not be found.</exception>
        public static object Instantiate(this IInjector self, Type @class, IReadOnlyDictionary <string, object?>?explicitArgs = null)
        {
            Ensure.Parameter.IsNotNull(self, nameof(self));
            Ensure.Parameter.IsNotNull(@class, nameof(@class));

            return(ServiceActivator.GetExtended(@class).Invoke(self, explicitArgs ?? new Dictionary <string, object?>(0)));
        }
示例#9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            //if (env.IsDevelopment())
            //{
            //    app.UseDeveloperExceptionPage();
            //}
            //else
            //{
            //app.UseExceptionHandler("/Home/Error");
            //// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            //app.UseHsts();
            //}

            ServiceActivator.Configure(app.ApplicationServices);

            app.UseExceptionHandler("/Error/Http500"); //500 numaralý kod çalýþtýrma hatalarý için

            app.UseHsts();

            app.UseHttpsRedirection();

            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
示例#10
0
        public void ActivateEmptyConstructor()
        {
            ServiceActivator activator = new ServiceActivator(typeof(Class1));
            var result = activator.Activate(Mock.Of <IContainer>());

            Assert.IsInstanceOfType(result, typeof(Class1));
        }
        public static IActionResult ShowMessage(this IActionResult actionResult,
                                                JConfirmMessageType messageType,
                                                string title,
                                                string content)
        {
            IHttpContextAccessor       contextAccessor;
            ITempDataDictionaryFactory tempDataFactory;

            contextAccessor = ServiceActivator.GetService <IHttpContextAccessor>();
            tempDataFactory = ServiceActivator.GetService <ITempDataDictionaryFactory>();

            var tempData = tempDataFactory.GetTempData(contextAccessor.HttpContext);

            var items = contextAccessor.HttpContext.Items;

            var tempDataKeyName = Constants.TempData.SuccessKey;

            switch (messageType)
            {
            case JConfirmMessageType.Error:
                tempDataKeyName = Constants.TempData.ErrorKey;
                break;

            case JConfirmMessageType.Warning:
                tempDataKeyName = Constants.TempData.WarningKey;
                break;
            }

            tempData[tempDataKeyName]             = content;
            tempData[Constants.TempData.TitleKey] = title;

            return(actionResult);
        }
示例#12
0
        public void GetLazyFactory_ShouldReturnProperFactory(string svcName)
        {
            var mockInjector = new Mock <IInjector>(MockBehavior.Strict);

            mockInjector
            .Setup(i => i.Get(It.IsAny <Type>(), It.IsAny <string>()))
            .Returns <Type, string>((type, name) => new Disposable());

            Func <IInjector, object> factory = ServiceActivator.GetLazyFactory(typeof(IDisposable), new OptionsAttribute {
                Name = svcName
            });

            Assert.That(factory, Is.Not.Null);

            Lazy <IDisposable> lazy = factory(mockInjector.Object) as Lazy <IDisposable>;

            Assert.That(lazy, Is.Not.Null);

            mockInjector.Verify(i => i.Get(It.IsAny <Type>(), It.IsAny <string>()), Times.Never);

            IDisposable retval = lazy.Value;

            Assert.That(retval, Is.InstanceOf <Disposable>());

            mockInjector.Verify(i => i.Get(It.Is <Type>(t => t == typeof(IDisposable)), It.Is <string>(s => s == svcName)), Times.Once);
        }
示例#13
0
        protected override async Task HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext)
        {
            // Decode request
            var request = await httpContext.Request.BodyReader.ReadSingleMessageAsync <TRequest>(serverCallContext, Method.RequestMarshaller.ContextualDeserializer);

            if (_pipelineInvoker == null)
            {
                var service = (TService)ServiceActivator.Create(serverCallContext, typeof(TService));
                try
                {
                    await _invoker(
                        service,
                        request,
                        new HttpContextStreamWriter <TResponse>(serverCallContext, Method.ResponseMarshaller.ContextualSerializer),
                        serverCallContext);
                }
                finally
                {
                    await ServiceActivator.ReleaseAsync(service);
                }
            }
            else
            {
                await _pipelineInvoker(
                    request,
                    new HttpContextStreamWriter <TResponse>(serverCallContext, Method.ResponseMarshaller.ContextualSerializer),
                    serverCallContext);
            }
        }
示例#14
0
        public void TestCreateCustom()
        {
            string          customType = typeof(CustomSnitch).AssemblyQualifiedName;
            IEndpointSnitch snitch     = ServiceActivator <Factory> .Create <IEndpointSnitch>(customType);

            Assert.IsTrue(snitch is CustomSnitch);
        }
示例#15
0
 /// <summary>
 /// Invoke the server streaming method with the specified <see cref="HttpContext"/>.
 /// </summary>
 /// <param name="httpContext">The <see cref="HttpContext"/> for the current request.</param>
 /// <param name="serverCallContext">The <see cref="ServerCallContext"/>.</param>
 /// <param name="request">The <typeparamref name="TRequest"/> message.</param>
 /// <param name="streamWriter">The <typeparamref name="TResponse"/> stream writer.</param>
 /// <returns>A <see cref="Task"/> that represents the asynchronous method.</returns>
 public async Task Invoke(HttpContext httpContext, ServerCallContext serverCallContext, TRequest request, IServerStreamWriter <TResponse> streamWriter)
 {
     if (_pipelineInvoker == null)
     {
         GrpcActivatorHandle <TService> serviceHandle = default;
         try
         {
             serviceHandle = ServiceActivator.Create(httpContext.RequestServices);
             await _invoker(
                 serviceHandle.Instance,
                 request,
                 streamWriter,
                 serverCallContext);
         }
         finally
         {
             if (serviceHandle.Instance != null)
             {
                 await ServiceActivator.ReleaseAsync(serviceHandle);
             }
         }
     }
     else
     {
         await _pipelineInvoker(
             request,
             streamWriter,
             serverCallContext);
     }
 }
示例#16
0
        public void TestRandomness()
        {
            IPAddress[] ips = new IPAddress[4];
            for (byte i = 0; i < ips.Length; ++i)
            {
                ips[i] = new IPAddress(new byte[] { 192, 168, 0, i });
            }

            IEndpointStrategy endpointStrategy = ServiceActivator <Factory> .Create <IEndpointStrategy>("Random", ips.AsEnumerable());

            List <IPAddress> alls = new List <IPAddress>();

            for (int i = 0; i < 10000; ++i)
            {
                IPAddress nextEndpoint = endpointStrategy.Pick(null);
                if (!alls.Contains(nextEndpoint))
                {
                    alls.Add(nextEndpoint);
                }
            }

            foreach (IPAddress ip in alls)
            {
                Assert.IsTrue(alls.Contains(ip));
            }
        }
示例#17
0
 public override IEnumerable <IAction> GetActions()
 {
     if (SoftwareViewModel.SelectedItem == null)
     {
         yield return(ServiceActivator.Create <BrowseAction>());
     }
 }
示例#18
0
 public UnitWorkContainer()
 {
     this.Add(ServiceActivator.Get <AddSpaceIndexerxUnitOfWork>());
     this.Add(ServiceActivator.Get <RemoveSpaceIndexerxUnitOfWork>());
     this.Add(ServiceActivator.Get <AddDocumentIndexerxUnitOfWork>());
     this.Add(ServiceActivator.Get <RemoveSpaceIndexerxUnitOfWork>());
 }
示例#19
0
 /// <summary>
 /// Invoke the client streaming method with the specified <see cref="HttpContext"/>.
 /// </summary>
 /// <param name="httpContext">The <see cref="HttpContext"/> for the current request.</param>
 /// <param name="serverCallContext">The <see cref="ServerCallContext"/>.</param>
 /// <param name="requestStream">The <typeparamref name="TRequest"/> reader.</param>
 /// <returns>A <see cref="Task{TResponse}"/> that represents the asynchronous method. The <see cref="Task{TResponse}.Result"/>
 /// property returns the <typeparamref name="TResponse"/> message.</returns>
 public async Task <TResponse> Invoke(HttpContext httpContext, ServerCallContext serverCallContext, IAsyncStreamReader <TRequest> requestStream)
 {
     if (_pipelineInvoker == null)
     {
         GrpcActivatorHandle <TService> serviceHandle = default;
         try
         {
             serviceHandle = ServiceActivator.Create(httpContext.RequestServices);
             return(await _invoker(
                        serviceHandle.Instance,
                        requestStream,
                        serverCallContext));
         }
         finally
         {
             if (serviceHandle.Instance != null)
             {
                 await ServiceActivator.ReleaseAsync(serviceHandle);
             }
         }
     }
     else
     {
         return(await _pipelineInvoker(
                    requestStream,
                    serverCallContext));
     }
 }
示例#20
0
        public ServerStreamingServerCallHandler(
            Method <TRequest, TResponse> method,
            ServerStreamingServerMethod <TService, TRequest, TResponse> invoker,
            GrpcServiceOptions serviceOptions,
            ILoggerFactory loggerFactory,
            IGrpcServiceActivator <TService> serviceActivator,
            IServiceProvider serviceProvider)
            : base(method, serviceOptions, loggerFactory, serviceActivator, serviceProvider)
        {
            _invoker = invoker;

            if (ServiceOptions.HasInterceptors)
            {
                ServerStreamingServerMethod <TRequest, TResponse> resolvedInvoker = async(resolvedRequest, responseStream, resolvedContext) =>
                {
                    GrpcActivatorHandle <TService> serviceHandle = default;
                    try
                    {
                        serviceHandle = ServiceActivator.Create(resolvedContext.GetHttpContext().RequestServices);
                        await _invoker(serviceHandle.Instance, resolvedRequest, responseStream, resolvedContext);
                    }
                    finally
                    {
                        if (serviceHandle.Instance != null)
                        {
                            ServiceActivator.Release(serviceHandle);
                        }
                    }
                };

                var interceptorPipeline = new InterceptorPipelineBuilder <TRequest, TResponse>(ServiceOptions.Interceptors, ServiceProvider);
                _pipelineInvoker = interceptorPipeline.ServerStreamingPipeline(resolvedInvoker);
            }
        }
示例#21
0
        protected override async Task HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext)
        {
            // Decode request
            var request = await httpContext.Request.BodyReader.ReadSingleMessageAsync <TRequest>(serverCallContext, Method.RequestMarshaller.ContextualDeserializer);

            if (_pipelineInvoker == null)
            {
                GrpcActivatorHandle <TService> serviceHandle = default;
                try
                {
                    serviceHandle = ServiceActivator.Create(httpContext.RequestServices);
                    await _invoker(
                        serviceHandle.Instance,
                        request,
                        new HttpContextStreamWriter <TResponse>(serverCallContext, Method.ResponseMarshaller.ContextualSerializer),
                        serverCallContext);
                }
                finally
                {
                    if (serviceHandle.Instance != null)
                    {
                        ServiceActivator.Release(serviceHandle);
                    }
                }
            }
            else
            {
                await _pipelineInvoker(
                    request,
                    new HttpContextStreamWriter <TResponse>(serverCallContext, Method.ResponseMarshaller.ContextualSerializer),
                    serverCallContext);
            }
        }
示例#22
0
        public void ExtendedActivator_ShouldThrowOnNonInterfaceArguments()
        {
            ConstructorInfo ctor = typeof(MyClass).GetConstructor(new[] { typeof(IDisposable), typeof(IList), typeof(int) });

            //
            // Sima Get() hivas nem fog mukodni (nem interface parameter).
            //

            Assert.Throws <ArgumentException>(() => ServiceActivator.Get(ctor), Resources.INVALID_CONSTRUCTOR);

            //
            // Ne mock-oljuk az injector-t h a megfelelo kiveteleket kapjuk
            //

            using (IServiceContainer container = new ServiceContainer())
            {
                IInjector injector = container
                                     .Factory <IDisposable>(i => new Disposable(), Lifetime.Scoped)
                                     .Factory <IList>(i => new List <object>(), Lifetime.Scoped)
                                     .CreateInjector();

                //
                // Ez mukodne viszont nem adtuk meg a nem interface parametert.
                //

                Assert.Throws <ArgumentException>(() => ServiceActivator.GetExtended(ctor).Invoke(injector, new Dictionary <string, object>(0)), Resources.PARAMETER_NOT_AN_INTERFACE);
            }
        }
        protected override async Task HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext)
        {
            // Disable request body data rate for client streaming
            DisableMinRequestBodyDataRateAndMaxRequestBodySize(httpContext);

            if (_pipelineInvoker == null)
            {
                GrpcActivatorHandle <TService> serviceHandle = default;
                try
                {
                    serviceHandle = ServiceActivator.Create(httpContext.RequestServices);
                    await _invoker(
                        serviceHandle.Instance,
                        new HttpContextStreamReader <TRequest>(serverCallContext, Method.RequestMarshaller.ContextualDeserializer),
                        new HttpContextStreamWriter <TResponse>(serverCallContext, Method.ResponseMarshaller.ContextualSerializer),
                        serverCallContext);
                }
                finally
                {
                    if (serviceHandle.Instance != null)
                    {
                        ServiceActivator.Release(serviceHandle);
                    }
                }
            }
            else
            {
                await _pipelineInvoker(
                    new HttpContextStreamReader <TRequest>(serverCallContext, Method.RequestMarshaller.ContextualDeserializer),
                    new HttpContextStreamWriter <TResponse>(serverCallContext, Method.ResponseMarshaller.ContextualSerializer),
                    serverCallContext);
            }
        }
示例#24
0
        protected override async Task HandleCallAsyncCore(HttpContext httpContext, HttpContextServerCallContext serverCallContext)
        {
            var request = await httpContext.Request.BodyReader.ReadSingleMessageAsync <TRequest>(serverCallContext, Method.RequestMarshaller.ContextualDeserializer);

            TResponse?response = null;

            if (_pipelineInvoker == null)
            {
                var service = (TService)ServiceActivator.Create(serverCallContext, typeof(TService));
                try
                {
                    response = await _invoker(service, request, serverCallContext);
                }
                finally
                {
                    await ServiceActivator.ReleaseAsync(service);
                }
            }
            else
            {
                response = await _pipelineInvoker(request, serverCallContext);
            }

            if (response == null)
            {
                // This is consistent with Grpc.Core when a null value is returned
                throw new RpcException(new Status(StatusCode.Cancelled, "No message returned from method."));
            }

            var responseBodyWriter = httpContext.Response.BodyWriter;
            await responseBodyWriter.WriteMessageAsync(response, serverCallContext, Method.ResponseMarshaller.ContextualSerializer, canFlush : false);
        }
示例#25
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            ServiceActivator.Configure(app.ApplicationServices);

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });
        }
示例#26
0
 public override IEnumerable <IAction> GetActions()
 {
     if (EjectViewModel.IsEject)
     {
         yield return(ServiceActivator.Create <EjectAction>());
     }
 }
示例#27
0
        public void TestCreateWithNull()
        {
            string       type  = null;
            const string key   = "tralala";
            const int    value = 42;

            Assert.Throws <ArgumentException>(() => ServiceActivator <FactoryWithCustomType> .Create <ITestService>(type, key, value));
        }
示例#28
0
        public override void Persist()
        {
            BeforePersist();
            IProjectImportService projectImportService = ServiceActivator.Get <IProjectImportService>();

            projectImportService.Import(_progressCounter, GetDto());
            AfterPersist();
        }
        protected virtual void Delete(ExecutionEvent executionEvent, Guid id)
        {
            ICRUDService <T> crudService = (ICRUDService <T>)ServiceActivator.Get(HandlerUtils.DTO_TO_SERVICE[typeof(T)]);

            Connection.GetInstance().StartTransaction();
            crudService.Delete(id);
            Connection.GetInstance().EndTransaction();
        }
示例#30
0
 public void GetLazyFactory_ShouldCache(string svcName)
 {
     Assert.AreSame(ServiceActivator.GetLazyFactory(typeof(IDisposable), new OptionsAttribute {
         Name = svcName
     }), ServiceActivator.GetLazyFactory(typeof(IDisposable), new OptionsAttribute {
         Name = svcName
     }));
 }