public static void AddBindAppModelConfiguation(this IServiceCollection services, IConfiguration configuration,
                                                       AppSettings appSettings)
        {
            configuration.Bind(appSettings);
            appSettings.PreLoadModelConfig();
            //判断是否为新环境,如果是环境执行初始化,判断的条件就是AppData下存不存在AppSettings.json文件
            var isInit = !AppSettingsHelper.ExistAppSettingsFile();

            var typeFinder    = new WebAppTypeFinder();
            var modelSettings = typeFinder.FindOfType <IAppModuleConfig>();
            var instances     = modelSettings
                                .Select(startup => (IAppModuleConfig)Activator.CreateInstance(startup));

            foreach (var appModelConfig in instances)
            {
                var nodeName = appModelConfig?.GetType().Name ?? "TempModel";
                configuration.GetSection($"ModuleConfigurations:{nodeName}").Bind(appModelConfig);

                if (isInit)
                {
                    appModelConfig?.Init();
                }
                appSettings.ModuleConfigurations.Add(nodeName, appModelConfig);
            }

            services.AddSingleton(appSettings);
            AppSettingsHelper.SaveAppSettings(appSettings);
        }
        public static IServiceProvider AddCustomIntegrations(this IServiceCollection services, IHostingEnvironment hostingEnvironment)
        {
            services.AddHttpContextAccessor();

            var fileProvider = new AppFileProvider(hostingEnvironment);
            var typeFinder   = new WebAppTypeFinder(fileProvider);

            //configure autofac
            var containerBuilder = new ContainerBuilder();

            //register type finder
            containerBuilder.RegisterInstance(fileProvider).As <IAppFileProvider>().SingleInstance();
            containerBuilder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();

            //populate Autofac container builder with the set of registered service descriptors
            containerBuilder.Populate(services);

            //find dependency registrars provided by other assemblies
            var dependencyRegistrars = typeFinder.FindClassesOfType <IDependencyRegistrar>();

            //create and sort instances of dependency registrars
            var instances = dependencyRegistrars
                            .Select(dependencyRegistrar => (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrar))
                            .OrderBy(dependencyRegistrar => dependencyRegistrar.Order);

            //register all provided dependencies
            foreach (var dependencyRegistrar in instances)
            {
                dependencyRegistrar.Register(containerBuilder, typeFinder);
            }

            return(new AutofacServiceProvider(containerBuilder.Build()));
        }
        /// <summary>
        /// Add and configure services
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        /// <returns>Service provider</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            ////find startup configurations provided by other assemblies
            var typeFinder            = new WebAppTypeFinder();
            var startupConfigurations = typeFinder.FindClassesOfType <IIntegratorStartup>();

            ////create and sort instances of startup configurations
            var instances = startupConfigurations
                            //.Where(startup => PluginManager.FindPlugin(startup)?.Installed ?? true) //ignore not installed plugins
                            .Select(startup => (IIntegratorStartup)Activator.CreateInstance(startup))
                            .OrderBy(startup => startup.Order);

            ////configure services
            foreach (var instance in instances)
            {
                instance.ConfigureServices(services, configuration);
            }

            ////register mapper configurations
            AddAutoMapper(services, typeFinder);

            ////register dependencies
            var IntegratorConfig = services.BuildServiceProvider().GetService <IntegratorConfig>();

            RegisterDependencies(IntegratorConfig, services, typeFinder);

            ////run startup tasks
            //if (!VaalBeachClubConfig.IgnoreStartupTasks)
            //    RunStartupTasks(typeFinder);

            ////resolve assemblies here. otherwise, plugins can throw an exception when rendering views
            //AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            return(_serviceProvider);
        }
Exemple #4
0
        /// <summary>
        /// Add and configure services
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        public void ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            //find startup configurations provided by other assemblies
            var typeFinder = new WebAppTypeFinder();

            //register engine
            services.AddSingleton <IEngine>(this);

            //register type finder
            services.AddSingleton <ITypeFinder>(typeFinder);

            ServiceProvider = services.BuildServiceProvider();

            var startupConfigurations = typeFinder.FindOfType <IAppModuleStartup>();

            //create and sort instances of startup configurations
            var instances = startupConfigurations
                            .Select(startup => (IAppModuleStartup)Activator.CreateInstance(startup))
                            .OrderBy(startup => startup.Order);

            //configure services
            foreach (var instance in instances)
            {
                instance.ConfigureServices(services, configuration);
            }

            //resolve assemblies here. otherwise, plugins can throw an exception when rendering views
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
        }
Exemple #5
0
        public override IList <Setting> GetAllSettings()
        {
            string directory             = new WebAppTypeFinder().GetBinDirectory();
            var    configurationBasePath = directory.Substring(0, directory.IndexOf("\\Tests\\Grand.Services.Tests\\") + 27);

            var configuration = new ConfigurationBuilder()
                                .SetBasePath(configurationBasePath)
                                .AddJsonFile("appsettingstest.json", optional: false, reloadOnChange: true)
                                .Build();

            var settings      = new List <Setting>();
            var settingObject = new ServiceCollection().ConfigureStartupConfig <ApplicationSettings>(configuration.GetSection("ApplicationSettingsSection"));
            var properties    = settingObject.GetType().GetProperties();

            foreach (var property in properties)
            {
                var value = settingObject.GetType().GetProperty(property.Name).GetValue(settingObject, null);
                settings.Add(new Setting
                {
                    Name    = property.Name.ToLowerInvariant(),
                    Value   = value.ToString(),
                    StoreId = ""
                });
            }

            return(settings);
        }
        public static void RegisterIValidatorType(this IServiceCollection services)
        {
            var typeFinder = new WebAppTypeFinder();

            var validatorTypes = typeFinder.FindOfType <IValidator>();

            foreach (var validatorType in validatorTypes)
            {
                var implementedInterface = validatorType.GetInterface("IValidator`1");
                if (implementedInterface != null)
                {
                    services.AddScoped(implementedInterface, validatorType);
                }
            }
            // foreach (var validatorType in types)
            // {
            //     var parentType =
            //         ((System.Reflection.TypeInfo) validatorType).ImplementedInterfaces.FirstOrDefault(x =>
            //             x.Name == "IValidator`1");
            //     if (parentType != null)
            //     {
            //         services.AddScoped(parentType, validatorType);
            //     }
            // }
        }
Exemple #7
0
        private void DependencyAutofacRegister(IContainer container)
        {
            Log.WriteLog("开始执行依赖注入......");
            var typeFinder = new WebAppTypeFinder();
            var builder    = new ContainerBuilder();

            try
            {
                //类型查询器依赖注入
                builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();
                builder.Update(container);


                //自定义依赖注入
                builder = new ContainerBuilder();
                var dependencyAutofacRegistrar = typeFinder.FindClassesOfType <IDependencyAutofacRegistrar>();
                List <IDependencyAutofacRegistrar> dependencyAutofacRegistrarList = new List <IDependencyAutofacRegistrar>();
                foreach (var dependencyAutofacRegistrarItem in dependencyAutofacRegistrar)
                {
                    dependencyAutofacRegistrarList.Add((IDependencyAutofacRegistrar)Activator.CreateInstance(dependencyAutofacRegistrarItem));
                }
                foreach (var dependencyAutofacRegistrarListItem in dependencyAutofacRegistrarList)
                {
                    Log.WriteLog($"正在注入{dependencyAutofacRegistrarListItem.GetType().FullName}类型");
                    dependencyAutofacRegistrarListItem.Register(builder, typeFinder);
                }
                builder.Update(container);
            }
            catch (Exception ex)
            {
                Log.WriteLog($"依赖注入失败,异常消息:{ex.Message}");
                throw;
            }
        }
Exemple #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc()
            .AddFluentValidation();

            var connectionString = Configuration["connectionStrings:AcmeDBConnectionString"];

            services.AddDbContext <AcmeDbContext>(o => o.UseSqlServer(connectionString));

            services.AddTransient <IRepository <City>, EfRepository <City> >();
            services.AddTransient <IRepository <Booking>, EfRepository <Booking> >();
            services.AddTransient <IRepository <Flight>, EfRepository <Flight> >();

            // Register the repositories
            services.AddScoped <IJourneyRepository, JourneyRepository>();

            // Register the services
            services.AddScoped <IFlightService, FlightService>();
            services.AddTransient <IValidator <FlightResourceParameters>, FlightResourceValidators>();
            services.AddTransient <IValidator <FlightViewModel>, FlightViewModelValidator>();


            var typeFinder = new WebAppTypeFinder();

            AddAutoMapper(services, typeFinder);
        }
Exemple #9
0
        /// <summary>
        /// 注册依赖
        /// </summary>
        /// <param name="config"></param>
        public virtual void RegisterDependencies(WebConfig config)
        {
            var builder   = new ContainerBuilder();
            var container = builder.Build();

            _containerManager = new ContainerManager(container);

            var typeFinder = new WebAppTypeFinder();

            builder = new ContainerBuilder();
            builder.RegisterInstance(config).As <WebConfig>().SingleInstance();
            builder.RegisterInstance(this).As <IEngine>().SingleInstance();
            builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();
            builder.Update(container);

            //register dependencies provided by other assemblies
            builder = new ContainerBuilder();
            var drTypes     = typeFinder.FindClassesOfType <IDependencyRegistrar>();
            var drInstances = drTypes.Select(drType => (IDependencyRegistrar)Activator.CreateInstance(drType)).ToList();

            //sort
            drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
            drInstances.ForEach(p => p.Register(builder, typeFinder, config));
            builder.Update(container);

            //set dependency resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Exemple #10
0
        /// <summary>
        /// Adds services for mediatR
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddMediator(this IServiceCollection services)
        {
            var typeFinder = new WebAppTypeFinder();
            var assemblies = typeFinder.GetAssemblies();

            services.AddMediatR(assemblies.ToArray());
        }
Exemple #11
0
        protected virtual void RegisterDependencies(IConfigurationSectionHandler config)
        {
            var builder   = new ContainerBuilder();
            var container = builder.Build();

            this._containerManager = new ContainerManager(container);

            //dependencies
            var typeFinder = new WebAppTypeFinder();

            builder = new ContainerBuilder();
            builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();
            builder.Update(container);



            //foreach (var dependencyRegistrar
            //               in new Type[]{
            //                   typeof(DependencyRegistrar)
            //                  ,typeof(Repos.DomainModel.Interface.DependencyRegistrar)
            //                  ,typeof(ReposDomain.Handlers.DependencyRegistrar)
            //               })

            //{
            //    var dep = (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrar);
            //    builder = new ContainerBuilder();
            //    dep.Register(builder, container, null, config, new DefaultConfOptions());
            //    builder.Update(container);
            //}

            ReqisterDependencies.DependencyRegister(container, config, new DefaultConfOptions());
        }
        /// <summary>
        /// Add and configure services
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        /// <returns>Service provider</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services, IConfiguration configuration)
        {
            //find startup configurations provided by other assemblies
            var typeFinder            = new WebAppTypeFinder();
            var startupConfigurations = typeFinder.FindClassesOfType <INopStartup>();

            //create and sort instances of startup configurations
            var instances = startupConfigurations
                            .Select(startup => (INopStartup)Activator.CreateInstance(startup))
                            .OrderBy(startup => startup.Order);

            ////configure services todo: MSSQL
            foreach (var instance in instances)
            {
                instance.ConfigureServices(services, configuration);
            }

            ////register mapper configurations
            //AddAutoMapper(services, typeFinder);

            //register dependencies
            //var nopConfig = services.BuildServiceProvider().GetService<NopConfig>();
            RegisterDependencies(services, typeFinder);//todo : ignore nopConfig

            ////run startup tasks
            //if (!nopConfig.IgnoreStartupTasks)
            //    RunStartupTasks(typeFinder);

            //resolve assemblies here. otherwise, plugins can throw an exception when rendering views
            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;

            return(_serviceProvider);
        }
        public void Configure(IApplicationBuilder application)
        {
            // application.ApplicationServices.GetRequiredService<IShardingBootstrapper>().Start();
            var logger = application.ApplicationServices.GetService(typeof(ILogger <object>)) as ILogger <object>;

            try
            {
                logger.LogInformation("开始执行数据库还原");
                var typeFinder = new WebAppTypeFinder();
                var dbContexts = typeFinder.FindOfType(typeof
                                                       (GirvsDbContext)).Where(x => !x.IsAbstract && !x.IsInterface).ToList();
                if (!dbContexts.Any())
                {
                    return;
                }


                foreach (var dbContext in dbContexts.Select(dbContextType =>
                                                            EngineContext.Current.Resolve(dbContextType) as GirvsDbContext))
                {
                    var dbConfig = EngineContext.Current.GetAppModuleConfig <DbConfig>()
                                   .GetDataConnectionConfig(dbContext.GetType());

                    if (dbConfig is { EnableAutoMigrate: true })
                    {
                        dbContext?.SwitchReadWriteDataBase(DataBaseWriteAndRead.Write);
                        dbContext?.Database.MigrateAsync().Wait();
                    }
                }
Exemple #14
0
        /// <summary>
        /// Register mapping
        /// </summary>
        /// <param name="config">Config</param>
        protected virtual void RegisterMapperConfiguration(/*NopConfig config*/)
        {
            //dependencies
            var typeFinder = new WebAppTypeFinder();

            //register mapper configurations provided by other assemblies
            var mcTypes     = typeFinder.FindClassesOfType <IMapperConfiguration>();
            var mcInstances = new List <IMapperConfiguration>();

            foreach (var mcType in mcTypes)
            {
                mcInstances.Add((IMapperConfiguration)Activator.CreateInstance(mcType));
            }
            //sort
            mcInstances = mcInstances.AsQueryable().OrderBy(t => t.Order).ToList();
            //get configurations
            var configurationActions = new List <Action <IMapperConfigurationExpression> >();

            foreach (var mc in mcInstances)
            {
                configurationActions.Add(mc.GetConfiguration());
            }
            //register
            AutoMapperConfiguration.Init(configurationActions);
        }
Exemple #15
0
        /// <summary>
        /// Register dependencies
        /// </summary>
        protected virtual void RegisterDependencies(/*NopConfig config*/)
        {
            var builder = new ContainerBuilder();

            //dependencies
            var typeFinder = new WebAppTypeFinder();

            //builder.RegisterInstance(config).As<NopConfig>().SingleInstance();
            builder.RegisterInstance(this).As <IEngine>().SingleInstance();
            builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();

            //register dependencies provided by other assemblies
            var drTypes     = typeFinder.FindClassesOfType <IDependencyRegistrar>();
            var drInstances = new List <IDependencyRegistrar>();

            foreach (var drType in drTypes)
            {
                drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drType));
            }
            //sort
            drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
            foreach (var dependencyRegistrar in drInstances)
            {
                dependencyRegistrar.Register(builder, typeFinder /*, config*/);
            }

            var container = builder.Build();

            this._containerManager = new ContainerManager(container);

            //set dependency resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Exemple #16
0
        /// <summary>
        /// Register dependencies
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="appSettings">App settings</param>
        public virtual void RegisterDependencies(IServiceCollection services, AppSettings appSettings)
        {
            var typeFinder = new WebAppTypeFinder();

            //register engine
            services.AddSingleton <IEngine>(this);

            //register type finder
            services.AddSingleton <ITypeFinder>(typeFinder);

            //find dependency registrars provided by other assemblies
            var dependencyRegistrars = typeFinder.FindOfType <IDependencyRegistrar>();

            //create and sort instances of dependency registrars
            var instances = dependencyRegistrars
                            .Select(dependencyRegistrar => (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrar))
                            .OrderBy(dependencyRegistrar => dependencyRegistrar.Order);

            //register all provided dependencies
            foreach (var dependencyRegistrar in instances)
            {
                dependencyRegistrar.Register(services, typeFinder, appSettings);
            }

            services.AddSingleton(services);
        }
Exemple #17
0
        public static void AddSettings(this IServiceCollection services)
        {
            var typeFinder = new WebAppTypeFinder();
            var settings   = typeFinder.FindClassesOfType <ISettings>();
            var instances  = settings.Select(x => (ISettings)Activator.CreateInstance(x));

            foreach (var item in instances)
            {
                services.AddScoped(item.GetType(), (x) =>
                {
                    var type           = item.GetType();
                    var storeId        = string.Empty;
                    var settingService = x.GetRequiredService <ISettingService>();
                    var storeContext   = x.GetRequiredService <IStoreContext>();
                    if (storeContext.CurrentStore == null)
                    {
                        storeId = ""; //storeContext.SetCurrentStore().Result.Id;
                    }
                    else
                    {
                        storeId = storeContext.CurrentStore.Id;
                    }

                    return(settingService.LoadSetting(type, storeId));
                });
            }
        }
Exemple #18
0
        public static WebAppTypeFinder TypeFinder(EngineSection config)
        {
            var context = new ThreadContext();
            var finder  = new WebAppTypeFinder(new TypeCache(new N2.Persistence.BasicTemporaryFileHelper(context)), config);

            finder.AssemblyRestrictToLoadingPattern = new System.Text.RegularExpressions.Regex("N2.Tests");
            return(finder);
        }
        private static Dictionary <string, Type> GetAllEnum()
        {
            var typeFinder = new WebAppTypeFinder();
            var assemblies = typeFinder.GetAssemblies()
                             .Where(x => x.FullName.Contains("Domain") || x.FullName.Contains("Application")).ToList();

            return(assemblies.Select(ass => ass.GetTypes().Where(x => x.IsEnum).ToList())
                   .Where(enumTypes => enumTypes.Any()).SelectMany(enumTypes => enumTypes).ToDictionary(item => item.Name));
        }
Exemple #20
0
        public static void AddCapSubscribe(this IServiceCollection services)
        {
            var typeFinder = new WebAppTypeFinder();
            var subscribes = typeFinder.FindOfType <ICapSubscribe>();

            foreach (var subscribe in subscribes)
            {
                services.AddScoped(subscribe);
            }
        }
Exemple #21
0
        public void SetUp()
        {
            assemblyCache = new TypeCache(new N2.Persistence.BasicTemporaryFileHelper(new ThreadContext()));
            var config = new N2.Configuration.EngineSection();

            config.Assemblies.SkipLoadingPattern = "nothing";
            config.Assemblies.Remove(new N2.Configuration.AssemblyElement("N2.Management"));
            config.Assemblies.EnableTypeCache = false;
            typeFinder = new WebAppTypeFinder(assemblyCache, config);
        }
        /// <summary>
        /// Adds authentication service
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddGrandAuthentication(this IServiceCollection services, IConfiguration configuration)
        {
            var config = new GrandConfig();

            configuration.GetSection("Grand").Bind(config);

            //set default authentication schemes
            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultScheme       = GrandCookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;
            });

            //add main cookie authentication
            authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.Name      = GrandCookieAuthenticationDefaults.CookiePrefix + GrandCookieAuthenticationDefaults.AuthenticationScheme;
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = GrandCookieAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = GrandCookieAuthenticationDefaults.AccessDeniedPath;

                options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
            });

            //add external authentication
            authenticationBuilder.AddCookie(GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme, options =>
            {
                options.Cookie.Name         = GrandCookieAuthenticationDefaults.CookiePrefix + GrandCookieAuthenticationDefaults.ExternalAuthenticationScheme;
                options.Cookie.HttpOnly     = true;
                options.LoginPath           = GrandCookieAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath    = GrandCookieAuthenticationDefaults.AccessDeniedPath;
                options.Cookie.SecurePolicy = config.CookieSecurePolicyAlways ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest;
            });

            //register external authentication plugins now
            var typeFinder = new WebAppTypeFinder();
            var externalAuthConfigurations = typeFinder.FindClassesOfType <IExternalAuthenticationRegistrar>();
            //create and sort instances of external authentication configurations
            var externalAuthInstances = externalAuthConfigurations
                                        .Where(x => PluginManager.FindPlugin(x)?.Installed ?? true) //ignore not installed plugins
                                        .Select(x => (IExternalAuthenticationRegistrar)Activator.CreateInstance(x))
                                        .OrderBy(x => x.Order);

            //configure services
            foreach (var instance in externalAuthInstances)
            {
                instance.Configure(authenticationBuilder, configuration);
            }

            services.AddSingleton <IAuthorizationPolicyProvider, PermisionPolicyProvider>();
            services.AddSingleton <IAuthorizationHandler, PermissionAuthorizationHandler>();
        }
Exemple #23
0
        ///// <summary>
        ///// Adds data protection services
        ///// 增加数据保护服务
        ///// </summary>
        ///// <param name="services">Collection of service descriptors</param>
        //public static void AddNopDataProtection(this IServiceCollection services)
        //{
        //    //check whether to persist data protection in Redis
        //    //检查是否在Redis中保存数据保护
        //    var nopConfig = services.BuildServiceProvider().GetRequiredService<NopConfig>();
        //    if (nopConfig.RedisEnabled && nopConfig.UseRedisToStoreDataProtectionKeys)
        //    {
        //        //store keys in Redis
        //        //使用Redis存储密钥
        //        services.AddDataProtection().PersistKeysToRedis(() =>
        //        {
        //            var redisConnectionWrapper = EngineContext.Current.Resolve<IRedisConnectionWrapper>();
        //            return redisConnectionWrapper.GetDatabase(nopConfig.RedisDatabaseId ?? (int)RedisDatabaseNumber.DataProtectionKeys);
        //        }, NopCachingDefaults.RedisDataProtectionKey);
        //    }
        //    else
        //    {
        //        var dataProtectionKeysPath = CommonHelper.DefaultFileProvider.MapPath("~/App_Data/DataProtectionKeys");
        //        var dataProtectionKeysFolder = new System.IO.DirectoryInfo(dataProtectionKeysPath);

        //        //configure the data protection system to persist keys to the specified directory
        //        services.AddDataProtection().PersistKeysToFileSystem(dataProtectionKeysFolder);
        //    }
        //}

        /// <summary>
        /// Adds authentication service
        /// 添加身份验证服务
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddNopAuthentication(this IServiceCollection services)
        {
            //set default authentication schemes
            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme = NopAuthenticationDefaults.AuthenticationScheme;
                options.DefaultScheme          = NopAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme    = NopAuthenticationDefaults.ExternalAuthenticationScheme;
            });

            //add main cookie authentication
            //添加主cookie身份验证
            authenticationBuilder.AddCookie(NopAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.Name      = $"{NopCookieDefaults.Prefix}{NopCookieDefaults.AuthenticationCookie}";
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = NopAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = NopAuthenticationDefaults.AccessDeniedPath;

                //whether to allow the use of authentication cookies from SSL protected page on the other store pages which are not
                //是否允许在其他不受SSL保护的存储页上使用来自SSL保护页的身份验证cookie
                options.Cookie.SecurePolicy = DataSettingsManager.DatabaseIsInstalled && EngineContext.Current.Resolve <SecuritySettings>().ForceSslForAllPages
                    ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
            });

            //add external authentication
            //添加外部验证
            authenticationBuilder.AddCookie(NopAuthenticationDefaults.ExternalAuthenticationScheme, options =>
            {
                options.Cookie.Name      = $"{NopCookieDefaults.Prefix}{NopCookieDefaults.ExternalAuthenticationCookie}";
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = NopAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = NopAuthenticationDefaults.AccessDeniedPath;

                //whether to allow the use of authentication cookies from SSL protected page on the other store pages which are not
                options.Cookie.SecurePolicy = DataSettingsManager.DatabaseIsInstalled && EngineContext.Current.Resolve <SecuritySettings>().ForceSslForAllPages
                    ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
            });

            //register and configure external authentication plugins now
            //现在注册并配置外部身份验证插件
            var typeFinder = new WebAppTypeFinder();
            var externalAuthConfigurations = typeFinder.FindClassesOfType <IExternalAuthenticationRegistrar>();
            var externalAuthInstances      = externalAuthConfigurations
                                             .Select(x => (IExternalAuthenticationRegistrar)Activator.CreateInstance(x));

            foreach (var instance in externalAuthInstances)
            {
                instance.Configure(authenticationBuilder);
            }
        }
        public static void RegisterCommandHandlerType(this IServiceCollection services)
        {
            var typeFinder          = new WebAppTypeFinder();
            var commandHandlerTypes = typeFinder.FindOfType <CommandHandler>()
                                      .Where(x => x.Name != nameof(CommandHandler));

            foreach (var commandHandlerType in commandHandlerTypes)
            {
                foreach (var @interface in commandHandlerType.GetInterfaces())
                {
                    services.AddScoped(@interface, commandHandlerType);
                }
            }
        }
        public static void RegisterNotificationHandlerType(this IServiceCollection services)
        {
            var typeFinder = new WebAppTypeFinder();
            var types      = typeFinder.FindOfType(typeof(INotificationHandler <>));

            foreach (var type in types)
            {
                // var implementedInterface = type.GetInterface("INotificationHandler`1");
                foreach (var implementedInterface in type.GetInterfaces())
                {
                    services.AddScoped(implementedInterface, type);
                }
            }
        }
        public static void RegisterManager(this IServiceCollection services)
        {
            var typeFinder            = new WebAppTypeFinder();
            var managerInterfaceTypes = typeFinder.FindOfType <IManager>(FindType.Interface)
                                        .Where(x => x.Name != nameof(IManager));

            foreach (var managerInterfaceType in managerInterfaceTypes)
            {
                var imp = typeFinder.FindOfType(managerInterfaceType).FirstOrDefault();
                if (imp != null && imp.IsClass)
                {
                    services.AddScoped(managerInterfaceType, imp);
                }
            }
        }
Exemple #27
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            ITypeFinder typeFinder      = new WebAppTypeFinder();
            var         typesToRegister = typeFinder.GetAssemblies().SelectMany(n => n.GetTypes()
                                                                                .Where(type => !String.IsNullOrEmpty(type.Namespace))
                                                                                .Where(type => type.BaseType != null && type.BaseType.IsGenericType &&
                                                                                       type.BaseType.GetGenericTypeDefinition() == typeof(EntityTypeConfiguration <>)));

            foreach (var type in typesToRegister)
            {
                dynamic configurationInstance = Activator.CreateInstance(type);
                modelBuilder.Configurations.Add(configurationInstance);
            }
        }
Exemple #28
0
        /// <summary>
        /// Adds authentication service
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddNopAuthentication(this IServiceCollection services)
        {
            //set default authentication schemes
            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultScheme       = NopCookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme = NopCookieAuthenticationDefaults.ExternalAuthenticationScheme;
            });

            //add main cookie authentication
            authenticationBuilder.AddCookie(NopCookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.Name      = NopCookieAuthenticationDefaults.CookiePrefix + NopCookieAuthenticationDefaults.AuthenticationScheme;
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = NopCookieAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = NopCookieAuthenticationDefaults.AccessDeniedPath;

                //whether to allow the use of authentication cookies from SSL protected page on the other store pages which are not
                options.Cookie.SecurePolicy = DataSettingsHelper.DatabaseIsInstalled() && EngineContext.Current.Resolve <SecuritySettings>().ForceSslForAllPages
                    ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
            });

            //add external authentication
            authenticationBuilder.AddCookie(NopCookieAuthenticationDefaults.ExternalAuthenticationScheme, options =>
            {
                options.Cookie.Name      = NopCookieAuthenticationDefaults.CookiePrefix + NopCookieAuthenticationDefaults.ExternalAuthenticationScheme;
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = NopCookieAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = NopCookieAuthenticationDefaults.AccessDeniedPath;

                //whether to allow the use of authentication cookies from SSL protected page on the other store pages which are not
                options.Cookie.SecurePolicy = DataSettingsHelper.DatabaseIsInstalled() && EngineContext.Current.Resolve <SecuritySettings>().ForceSslForAllPages
                    ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
            });

            //register and configure external authentication plugins now
            var typeFinder = new WebAppTypeFinder();
            var externalAuthConfigurations = typeFinder.FindClassesOfType <IExternalAuthenticationRegistrar>();
            var externalAuthInstances      = externalAuthConfigurations
                                             .Where(x => PluginManager.FindPlugin(x)?.Installed ?? true) //ignore not installed plugins
                                             .Select(x => (IExternalAuthenticationRegistrar)Activator.CreateInstance(x));

            foreach (var instance in externalAuthInstances)
            {
                instance.Configure(authenticationBuilder);
            }
        }
Exemple #29
0
        /// <summary>
        /// Adds authentication service
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        public static void AddSmiAuthentication(this IServiceCollection services)
        {
            //set default authentication schemes
            var authenticationBuilder = services.AddAuthentication(options =>
            {
                options.DefaultChallengeScheme = SmiAuthenticationDefaults.AuthenticationScheme;
                options.DefaultScheme          = SmiAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme    = SmiAuthenticationDefaults.ExternalAuthenticationScheme;
            });

            //add main cookie authentication
            authenticationBuilder.AddCookie(SmiAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.Name      = $"{SmiCookieDefaults.Prefix}{SmiCookieDefaults.AuthenticationCookie}";
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = SmiAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = SmiAuthenticationDefaults.AccessDeniedPath;

                //whether to allow the use of authentication cookies from SSL protected page on the other store pages which are not
                options.Cookie.SecurePolicy = DataSettingsManager.DatabaseIsInstalled && EngineContext.Current.Resolve <IStoreContext>().CurrentStore.SslEnabled
                    ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
            });

            //add external authentication
            authenticationBuilder.AddCookie(SmiAuthenticationDefaults.ExternalAuthenticationScheme, options =>
            {
                options.Cookie.Name      = $"{SmiCookieDefaults.Prefix}{SmiCookieDefaults.ExternalAuthenticationCookie}";
                options.Cookie.HttpOnly  = true;
                options.LoginPath        = SmiAuthenticationDefaults.LoginPath;
                options.AccessDeniedPath = SmiAuthenticationDefaults.AccessDeniedPath;

                //whether to allow the use of authentication cookies from SSL protected page on the other store pages which are not
                options.Cookie.SecurePolicy = DataSettingsManager.DatabaseIsInstalled && EngineContext.Current.Resolve <IStoreContext>().CurrentStore.SslEnabled
                    ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.None;
            });

            //register and configure external authentication plugins now
            var typeFinder = new WebAppTypeFinder();
            var externalAuthConfigurations = typeFinder.FindClassesOfType <IExternalAuthenticationRegistrar>();
            var externalAuthInstances      = externalAuthConfigurations
                                             .Select(x => (IExternalAuthenticationRegistrar)Activator.CreateInstance(x));

            foreach (var instance in externalAuthInstances)
            {
                instance.Configure(authenticationBuilder);
            }
        }
        /// <summary>
        /// Register dependencies
        /// </summary>
        /// <param name="config">Config</param>
        protected virtual void RegisterDependencies(CmsConfig config)
        {
            var typeFinder = new WebAppTypeFinder(config);

            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());
            builder.RegisterFilterProvider();
            builder.RegisterSource(new ViewRegistrationSource());

            var container = builder.Build();

            //we create new instance of ContainerBuilder
            //because Build() or Update() method can only be called once on a ContainerBuilder.

            //dependencies

            builder = new ContainerBuilder();
            builder.RegisterInstance(config).As <CmsConfig>().SingleInstance();
            builder.RegisterInstance(this).As <IEngine>().SingleInstance();
            builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();

            builder.Update(container);

            //register dependencies provided by other assemblies
            builder = new ContainerBuilder();
            var drTypes     = typeFinder.FindClassesOfType <IDependencyRegistrar>();
            var drInstances = new List <IDependencyRegistrar>();

            foreach (var drType in drTypes)
            {
                drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drType));
            }
            //sort
            drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
            foreach (var dependencyRegistrar in drInstances)
            {
                dependencyRegistrar.Register(builder, typeFinder);
            }
            builder.Update(container);

            this._containerManager = new ContainerManager(container);

            //set dependency resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }