static void Main(string[] args)
        {
            Console.WriteLine("Dependency Injection Demo (3)");
            Console.WriteLine("Alternative implementations and Guids");
            Console.WriteLine("-------------------------------------");
            var services = new ServiceCollection();

            services.AddSingleton <IXMLWriter, XMLWriter>();
            var provider = services.BuildServiceProvider();

            var XMLInstance = provider.GetService <IXMLWriter>();

            XMLInstance.WriteXML();

            var XMLInstance2 = ServiceProviderServiceExtensions.
                               GetService <IXMLWriter>(provider);

            XMLInstance2.WriteXML();

            // Provider via DefaultServiceProviderFactory
            //var factory = new DefaultServiceProviderFactory();
            //IServiceProvider prov = factory.CreateServiceProvider(services);

            // Provider via ServiceCollectionContainerBuilderExtensions
            //IServiceProvider prov = ServiceCollectionContainerBuilderExtensions.
            //                        BuildServiceProvider(services);
            //var XMLInstance = prov.GetService<IXMLWriter>();
            //XMLInstance.WriteXML();

            Console.ReadLine();
        }
Exemplo n.º 2
0
 public override void OnActionExecuting(ActionExecutingContext context)
 {
     //IL_00ce: Unknown result type (might be due to invalid IL or missing references)
     //IL_00d3: Unknown result type (might be due to invalid IL or missing references)
     //IL_00da: Unknown result type (might be due to invalid IL or missing references)
     //IL_00e1: Unknown result type (might be due to invalid IL or missing references)
     //IL_010d: Expected O, but got Unknown
     if (CurrentUser != null)
     {
         HttpContext httpContext = context.HttpContext;
         string      text        = httpContext.Request.Cookies["pc"];
         if (text != null)
         {
             ((dynamic)this.ViewBag).UserPromotionCount = text;
         }
         else
         {
             IPromotionService service = ServiceProviderServiceExtensions.GetService <IPromotionService>(httpContext.RequestServices);
             Result <int>      result  = service.GetUserActivePromotionCount(CurrentUser.UserId).Result;
             int data = result.Data;
             IResponseCookies cookies = httpContext.Response.Cookies;
             string           text2   = data.ToString();
             CookieOptions    val     = new CookieOptions();
             val.HttpOnly = (true);
             val.Secure   = (true);
             val.Expires  = ((DateTimeOffset?)DateTime.Now.AddMinutes(1.0));
             cookies.Append("pc", text2, val);
             ((dynamic)this.ViewBag).UserPromotionCount = data.ToString();
         }
     }
     base.OnActionExecuting(context);
 }
        public JsonResult ProductInformation([Bind(Prefix = "id")] string productId)
        {
            var service = ServiceProviderServiceExtensions.GetService <IVisitorContext>(ServiceLocator.ServiceProvider);
            var product = _arRepository.GetProductInformation(service, productId);

            return(Json(product, JsonRequestBehavior.AllowGet));
        }
Exemplo n.º 4
0
 private IShellPipeline BuildTenantPipeline()
 {
     V_0            = new ApplicationBuilder(ShellScope.get_Context().get_ServiceProvider(), this._features);
     stackVariable7 = ServiceProviderServiceExtensions.GetService <IEnumerable <IStartupFilter> >(V_0.get_ApplicationServices());
     V_1            = new ShellRequestPipeline();
     V_2            = new Action <IApplicationBuilder>(this.u003cBuildTenantPipelineu003eb__6_0);
     V_3            = stackVariable7.Reverse <IStartupFilter>().GetEnumerator();
     try
     {
         while (V_3.MoveNext())
         {
             V_2 = V_3.get_Current().Configure(V_2);
         }
     }
     finally
     {
         if (V_3 != null)
         {
             V_3.Dispose();
         }
     }
     V_2.Invoke(V_0);
     V_1.set_Next(V_0.Build());
     return(V_1);
 }
Exemplo n.º 5
0
 protected static string[] GetDependencies(IDatabaseRepository databaseRepository)
 {
     if (databaseRepository == null)
     {
         databaseRepository = ServiceProviderServiceExtensions.GetService <IDatabaseRepository>(ServiceLocator.ServiceProvider);
     }
     return((databaseRepository.GetContentDatabase().Name.ToLower() == GlobalSettings.Database.Master) ? AssetContentRefresher.MasterCacheDependencyKeys : AssetContentRefresher.WebCacheDependencyKeys);
 }
Exemplo n.º 6
0
        public static void RegisterCache(this IServiceCollection services, IConfiguration configuration)
        {
            services.Configure <RedisSettings>(option =>
            {
                var jsonFileConfig = configuration.GetSection(nameof(RedisSettings));
                option.Host        = jsonFileConfig.GetValue <string>(nameof(RedisSettings.Host));
                option.Password    = jsonFileConfig.GetValue <string>(nameof(RedisSettings.Password));
            });

            services.AddSingleton <IRedisStore, RedisStore>();
            services.AddSingleton <IRedisClientFactory, RedisClientFactory>();
            services.AddTransient(serviceProvider => ServiceProviderServiceExtensions.GetService <IRedisClientFactory>(serviceProvider).GetDatabase());
            services.AddMemoryCache(setup => { setup.ExpirationScanFrequency = TimeSpan.FromMinutes(1); });
        }
        public static IUserContext GetUserContext(this IServiceProvider container, IUserContext userContext)
        {
            IUserContext userContext1 = userContext;

            try
            {
                if (ServiceProviderServiceExtensions.GetService <IUserContextLoader>(container) != null)
                {
                    ServiceProviderServiceExtensions.GetService <IUserContextLoader>(container).Load(userContext1);
                }
            }
            catch
            {
            }
            return(userContext1);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Method to clear expired persisted grants.
        /// </summary>
        /// <returns></returns>
        public async Task RemoveExpiredGrantsAsync()
        {
            try
            {
                _logger.LogTrace("Querying for expired grants to remove");

                var found = Int32.MaxValue;

                using (var serviceScope = _serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
                {
                    var tokenCleanupNotification = ServiceProviderServiceExtensions.GetService <IOperationalStoreNotification>(serviceScope.ServiceProvider);
                    {
                        while (found >= _options.TokenCleanupBatchSize)
                        {
                            var expired = PersistedGrants.FindAllByExpirationAndBatchSize(_options.TokenCleanupBatchSize);

                            found = expired.Count;
                            _logger.LogInformation("Removing {grantCount} grants", found);

                            if (found > 0)
                            {
                                try
                                {
                                    expired.Delete();

                                    if (tokenCleanupNotification != null)
                                    {
                                        await tokenCleanupNotification.PersistedGrantsRemovedAsync(expired);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    // we get this if/when someone else already deleted the records
                                    // we want to essentially ignore this, and keep working
                                    _logger.LogDebug("Concurrency exception removing expired grants: {exception}", ex.Message);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError("Exception removing expired grants: {exception}", ex.Message);
            }
        }
 /// <summary>
 /// Uses the SQLite cache.
 /// </summary>
 /// <returns>The SQLite cache.</returns>
 /// <param name="app">App.</param>
 public static IApplicationBuilder UseLiteXSQLiteCache(this IApplicationBuilder app)
 {
     try
     {
         SqliteConnection connection = ServiceProviderServiceExtensions.GetService <ISQLiteConnectionProvider>(app.ApplicationServices).GetConnection();
         if (((DbConnection)connection).State == ConnectionState.Closed)
         {
             ((DbConnection)connection).Open();
         }
         SqlMapper.Execute((IDbConnection)connection, "CREATE TABLE IF NOT EXISTS [litexcache] (\r\n                    [ID] INTEGER PRIMARY KEY\r\n                    , [cachekey] TEXT\r\n                    , [cachevalue] TEXT\r\n                    , [expiration] INTEGER)", (object)null, (IDbTransaction)null, (int?)null, (CommandType?)null);
         return(app);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(app);
     }
 }
Exemplo n.º 10
0
        /// <summary>
        /// 记录异常日志。
        /// </summary>
        /// <param name="filterContext"></param>
        protected virtual void LogException(ExceptionContext filterContext)
        {
            var controllerName = (string)filterContext.RouteData.Values["controller"];
            var actionName     = (string)filterContext.RouteData.Values["action"];

            Tracer.Error($"Throw exception when '{controllerName}.{actionName}' is executed:\n{filterContext.Exception.Output()}");

            //记录日志
#if !NETCOREAPP
            var logger = LoggerFactory.CreateLogger();
#else
            var logger = ServiceProviderServiceExtensions.GetService <ILogger>(filterContext.HttpContext.RequestServices);
#endif
            if (logger != null)
            {
                logger.Error(string.Format("执行控制器 {0} 的方法 {1} 时发生错误。",
                                           controllerName, actionName), filterContext.Exception);
            }
        }
Exemplo n.º 11
0
        public static void UseStaticCommands(this IAppBuilder builder, StaticCommandsList staticCommands)
        {
            builder.UsePossibleCommands();
            builder.Services.TryAddSingleton(provider =>
            {
                ServiceProviderServiceExtensions.GetService <ILogger>(provider)
                ?.Debug("Loaded {Count} static commands: {Commands}",
                        staticCommands.StaticCommandsTypes.Count,
                        string.Join(", ", staticCommands.StaticCommandsTypes.Select(a => a.Name)));

                return(staticCommands);
            });
            builder.UseMiddleware <StaticCommandsMiddleware>();

            foreach (var command in staticCommands.StaticCommandsTypes)
            {
                builder.Services.AddScoped(command);
            }
        }
Exemplo n.º 12
0
        public IFilterMetadata CreateInstance(IServiceProvider serviceProvider)
        {
            if (Policy != null || (object)PolicyProvider != null)
            {
                return(this);
            }
            IAuthorizationPolicyProvider requiredService = ServiceProviderServiceExtensions.GetRequiredService <IAuthorizationPolicyProvider>(serviceProvider);

            if (PolicyProvider == null)
            {
                PolicyProvider = ServiceProviderServiceExtensions.GetRequiredService <IAuthorizationPolicyProvider>(serviceProvider);
            }
            if (Policy == null)
            {
                Policy = AuthorizationPolicy.CombineAsync(requiredService, AuthorizeData).GetAwaiter().GetResult();
            }
            if (AuthorizeFilter == null)
            {
                AuthorizeFilter = ServiceProviderServiceExtensions.GetService <IAuthorizeFilter>(serviceProvider);
            }
            return(this);
        }
Exemplo n.º 13
0
        // Big hack, tests fails if only call AddHangfire because Hangfire fail at initializing at the second test run
        private void AddHangfireFix(IServiceCollection services)
        {
            Action <IGlobalConfiguration> configuration = o =>
            {
                var scope   = AspNetCoreJobActivator.Current.BeginScope(null);
                var options = (ApplicationDbContextFactory)scope.Resolve(typeof(ApplicationDbContextFactory));
                options.ConfigureHangfireBuilder(o);
            };

            ServiceCollectionDescriptorExtensions.TryAddSingleton <Action <IGlobalConfiguration> >(services, (IServiceProvider serviceProvider) => new Action <IGlobalConfiguration>((config) =>
            {
                ILoggerFactory service = ServiceProviderServiceExtensions.GetService <ILoggerFactory>(serviceProvider);
                if (service != null)
                {
                    Hangfire.GlobalConfigurationExtensions.UseLogProvider <AspNetCoreLogProvider>(config, new AspNetCoreLogProvider(service));
                }
                IServiceScopeFactory service2 = ServiceProviderServiceExtensions.GetService <IServiceScopeFactory>(serviceProvider);
                if (service2 != null)
                {
                    Hangfire.GlobalConfigurationExtensions.UseActivator <AspNetCoreJobActivator>(config, new AspNetCoreJobActivator(service2));
                }
                configuration(config);
            }));

            services.AddHangfire(configuration);
            services.AddCors(o =>
            {
                o.AddPolicy("BitpayAPI", b =>
                {
                    b.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
                });
            });

            services.Configure <IOptions <ApplicationInsightsServiceOptions> >(o =>
            {
                o.Value.DeveloperMode = _Env.IsDevelopment();
            });
        }
Exemplo n.º 14
0
 private IHostingEnvironment GetHostingEnvironment(ExceptionContext context)
 {
     return(ServiceProviderServiceExtensions.GetService <IHostingEnvironment>(context.HttpContext.RequestServices));
 }
Exemplo n.º 15
0
 private IModelMetadataProvider GetModelMetadataProvider(ExceptionContext context)
 {
     return(ServiceProviderServiceExtensions.GetService <IModelMetadataProvider>(context.HttpContext.RequestServices));
 }
Exemplo n.º 16
0
 public T GetService <T>()
 {
     return(ServiceProviderServiceExtensions.GetService <T>(this));
 }
Exemplo n.º 17
0
 private static ILoggerFactory GetLoggerFactory(ExceptionContext context)
 {
     return(ServiceProviderServiceExtensions.GetService <ILoggerFactory>(context.HttpContext.RequestServices));
 }
 private IAssemblyProviderResolveCallback GetResolveCallback()
 {
     return(ServiceProviderServiceExtensions.GetService <IAssemblyProviderResolveCallback>(ServiceProvider));
 }
Exemplo n.º 19
0
 private IStringLocalizer GetStringLocalizer(ExceptionContext context)
 {
     return(ServiceProviderServiceExtensions.GetService <IStringLocalizer>(context.HttpContext.RequestServices));
 }
Exemplo n.º 20
0
 private IMongoUnitOfWork GetUnitOfWork(ExceptionContext context)
 {
     return(ServiceProviderServiceExtensions.GetService <IMongoUnitOfWork>(context.HttpContext.RequestServices));
 }
 public static bool IsRelational(this DatabaseFacade database)
 {
     return(ServiceProviderServiceExtensions.GetService <IRelationalConnection>(AccessorExtensions.GetInfrastructure(database)) != null);
 }
Exemplo n.º 22
0
 public static IMenuItemsRenderer GetMenuItemsRenderer(ViewContext context)
 {
     return(ServiceProviderServiceExtensions.GetService <IMenuItemsRenderer>(context.HttpContext.RequestServices));
 }
Exemplo n.º 23
0
 public CustomizableTaxonomyProvider()
 {
     _tagsSettingService  = ServiceProviderServiceExtensions.GetService <ICustomTaggerSettingService>(ServiceLocator.ServiceProvider);
     _tagsCategoryService = ServiceProviderServiceExtensions.GetService <ICustomizableTagCategoryService>(ServiceLocator.ServiceProvider);
     _tagsEntryService    = ServiceProviderServiceExtensions.GetService <ICustomizableTagEntryService>(ServiceLocator.ServiceProvider);
 }
Exemplo n.º 24
0
        public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            AuthorizationPolicy effectivePolicy = Policy;

            if (effectivePolicy == null)
            {
                if (PolicyProvider == null)
                {
                    throw new InvalidOperationException("An AuthorizationPolicy cannot be created without a valid instance of IAuthorizationPolicyProvider.");
                }
                effectivePolicy = await AuthorizationPolicy.CombineAsync(PolicyProvider, AuthorizeData);
            }
            if (effectivePolicy != null)
            {
                MvcPrincipal newPrincipal  = null;
                string       currentScheme = effectivePolicy.AuthenticationSchemes.FirstOrDefault();
                if (!string.IsNullOrEmpty(currentScheme))
                {
                    if (!(context.HttpContext.User.Identity is MvcIdentity) || !context.HttpContext.User.Identity.IsAuthenticated)
                    {
                        string cookie = CookieUtil.GetCookie(currentScheme, true);
                        if (!string.IsNullOrEmpty(cookie))
                        {
                            try
                            {
                                string      value    = DataProtectionUtil.UnProtect(cookie);
                                MvcIdentity identity = JsonExtension.GetModel <MvcIdentity>(value, "");
                                if (identity != null)
                                {
                                    newPrincipal = identity.GetPrincipal();
                                }
                            }
                            catch
                            {
                            }
                        }
                    }
                    else
                    {
                        newPrincipal = (context.HttpContext.User as MvcPrincipal);
                    }
                }
                if (newPrincipal == null)
                {
                    context.HttpContext.User = MvcIdentity.Instance.GetPrincipal();
                }
                else
                {
                    context.HttpContext.User = newPrincipal;
                }
                if (!context.Filters.Any((IFilterMetadata item) => item is IAllowAnonymousFilter))
                {
                    if (context.HttpContext.User.Identity.IsAuthenticated)
                    {
                        if (AuthorizeFilter == null)
                        {
                            AuthorizeFilter = ServiceProviderServiceExtensions.GetService <IAuthorizeFilter>(context.HttpContext.RequestServices);
                        }
                        if (AuthorizeFilter != null)
                        {
                            await AuthorizeFilter.OnAuthorizedAsync(context, currentScheme);
                        }
                    }
                    else
                    {
                        context.Result = new ChallengeResult(effectivePolicy.AuthenticationSchemes.ToArray());
                    }
                }
            }
        }
Exemplo n.º 25
0
        public static IUrlHelper GetUrlHelper(ViewContext context)
        {
            var factory = ServiceProviderServiceExtensions.GetService <IUrlHelperFactory>(context.HttpContext.RequestServices);

            return(factory.GetUrlHelper(context));
        }
Exemplo n.º 26
0
 public Task ExecuteDbContextAsync(Func <FooContext, Task> action)
 {
     return(ExecuteScopeAsync(sp => action(ServiceProviderServiceExtensions.GetService <FooContext>(sp))));
 }
Exemplo n.º 27
0
 private IHisarExceptionFilter GetHisarExceptionFilter(ExceptionContext context)
 {
     return(ServiceProviderServiceExtensions.GetService <IHisarExceptionFilter>(context.HttpContext.RequestServices));
 }
 public CustomizableTagger()
 {
     _settingsService = ServiceProviderServiceExtensions.GetService <ICustomTaggerSettingService>(ServiceLocator.ServiceProvider);
 }
Exemplo n.º 29
0
 private IClaimsProvider GetClaimsProvider(ExceptionContext context)
 {
     return(ServiceProviderServiceExtensions.GetService <IClaimsProvider>(context.HttpContext.RequestServices));
 }
 private static RunningComponentHelper GetComponentHelper(IServiceProvider applicationServices)
 {
     return(ServiceProviderServiceExtensions.GetService <RunningComponentHelper>(applicationServices));
 }