Esempio n. 1
0
        public static AppStartup ConfigAliyunOSS(this AppStartup startup, IConfiguration configuration, ContainerBuilder builder = null)
        {
            if (configuration == null)
            {
                throw new Exception("配置configuration不能为空");
            }
            if (builder == null && EasyIocContainer.Container != null)
            {
                throw new Exception("注册AliyunOSS必须在InitIoC容器生成之前完成!");
            }

            string endpoint        = configuration["appSettings:AliyunOSS.Endpoint"];
            string accessKeyId     = configuration["appSettings:AliyunOSS.AccessKeyId"];
            string accessKeySecret = configuration["appSettings:AliyunOSS.AccessKeySecret"];

            var aliyunOSS = new AliyunOSS(endpoint, accessKeyId, accessKeySecret);

            if (builder == null)
            {
                EasyAutofac.ContainerBuilder.Register(c => aliyunOSS).As <AliyunOSS>().PropertiesAutowired().SingleInstance();
            }
            else
            {
                builder.Register(c => aliyunOSS).As <AliyunOSS>().PropertiesAutowired().SingleInstance();
            }

            return(startup);
        }
Esempio n. 2
0
        /// <summary>
        /// 初始化缓存服务
        /// </summary>
        public static AppStartup RegRedisCache(this AppStartup startup, ContainerBuilder builder = null, TimeSpan?cacheExpires = null)
        {
            if (builder == null && EasyIocContainer.Container != null)
            {
                throw new Exception("注册Redis必须在InitIoC容器生成之前完成!");
            }

            RedisCache redisCache = null;

            if (cacheExpires == null)
            {
                redisCache = new RedisCache();
            }
            else
            {
                redisCache = new RedisCache(cacheExpires.Value);
            }

            if (builder == null)
            {
                EasyAutofac.ContainerBuilder.Register(c => redisCache).As <IEasyCache>().PropertiesAutowired().SingleInstance();
            }
            else
            {
                builder.Register(c => redisCache).As <IEasyCache>().PropertiesAutowired().SingleInstance();
            }

            return(startup);
        }
Esempio n. 3
0
        public static AppStartup UseNLog(this AppStartup startup, string nlogFilePath)
        {
            if (!File.Exists(nlogFilePath))
            {
                throw new FileNotFoundException("未找到nlog配置文件");
            }

            LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration(nlogFilePath);

            return(startup);
        }
Esempio n. 4
0
        /// <summary>
        /// 初始化全局IoC容器
        /// </summary>
        public static AppStartup InitIoC(this AppStartup startup, IServiceLocator serviceLocator)
        {
            if (serviceLocator == null)
            {
                throw new Exception("IServiceLocator对象不能为空");
            }

            EasyIocContainer.InitIocContainer(serviceLocator);

            return(startup);
        }
Esempio n. 5
0
        /// <summary>
        /// 初始化MQ消费者事件绑定(在IOC容器生成后执行)
        /// </summary>
        public static AppStartup BindMqConsumer(this AppStartup startup)
        {
            if (EasyIocContainer.Container == null)
            {
                throw new Exception("初始化MQ消费者事件绑定必须在IOC容器生成后执行!");
            }

            var binder = EasyIocContainer.GetInstance <IMqConsumerBinder>();

            binder.BindConsumer();

            return(startup);
        }
Esempio n. 6
0
        public static AppStartup RegExtraIoC(this AppStartup startup, ContainerBuilder builder = null)
        {
            if (builder == null)
            {
                new EasyAutofac().RegExtraIoc(hasExtraIocReg: true);
            }
            else
            {
                new EasyAutofac(builder).RegExtraIoc(hasExtraIocReg: true);
            }

            return(startup);
        }
Esempio n. 7
0
        /// <summary>
        /// 获取需要防御流量攻击的【Action】
        /// </summary>
        public static AppStartup InitLimitAttack(this AppStartup startup, WebType webType, Assembly assembly)
        {
            var limitAttackModelList = new List <DefendAttackModel>();

            if (webType == WebType.Mvc)
            {
                limitAttackModelList = DefendAttack_Mvc.GetLimitAttackModel(assembly);
            }
            else if (webType == WebType.WebApi)
            {
                limitAttackModelList = DefendAttack_WebApi.GetLimitAttackModel(assembly);
            }

            DefendAttackContainer.InitDefendAttackList(limitAttackModelList, assembly.GetName().Name);

            return(startup);
        }
Esempio n. 8
0
        /// <summary>
        /// 初始化机器线程池配置
        /// </summary>
        /// <param name="minWorkerThreads">最小工作线程数(每个逻辑CPU核心最优应设置为50,例如当前是4核CPU,那么该参数应为:4 * 50 = 200)</param>
        /// <param name="minIoThreads">最小IO线程数(每个逻辑CPU核心最优应设置为50,例如当前是4核CPU,那么该参数应为:4 * 50 = 200)</param>
        public static AppStartup InitMachineConfig(this AppStartup startup, int minWorkerThreads = 200, int minIoThreads = 200)
        {
            ThreadPool.SetMinThreads(minWorkerThreads, minIoThreads);

            ThreadPool.GetMinThreads(out int minWorkThread, out int minIOThread);
            ThreadPool.GetMaxThreads(out int maxWorkThread, out int maxIOThread);
            ThreadPool.GetAvailableThreads(out int workThread, out int completeThread);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"最大工作线程:{maxWorkThread},最大IO线程:{maxIOThread}");
            sb.AppendLine($"最小工作线程:{minWorkThread},最小IO线程:{minIOThread}");
            sb.AppendLine($"可用工作线程:{workThread},可用IO线程:{completeThread}");

            logger.Info(sb.ToString());

            return(startup);
        }
Esempio n. 9
0
        public static AppStartup RegConfig(this AppStartup startup, IConfiguration configuration, ContainerBuilder builder = null)
        {
            if (configuration == null)
            {
                throw new Exception("配置configuration不能为空");
            }

            if (builder != null)
            {
                builder.Register(c => configuration).As <IConfiguration>().PropertiesAutowired().SingleInstance();
            }
            else
            {
                EasyAutofac.ContainerBuilder.Register(c => configuration).As <IConfiguration>().PropertiesAutowired().SingleInstance();
            }

            return(startup);
        }
Esempio n. 10
0
        /// <summary>
        /// 测试Redis是否连接成功
        /// </summary>
        public static AppStartup CheckRedis(this AppStartup startup)
        {
            if (EasyIocContainer.Container == null)
            {
                throw new Exception("CheckRedis必须在IOC容器生成后执行!");
            }

            try
            {
                RedisManager.Connection.GetDatabase(0);
            }
            catch (Exception ex)
            {
                logger.Error(ex, "连接Redis服务器失败");
            }

            return(startup);
        }
Esempio n. 11
0
        /// <summary>
        /// 初始化MEF容器
        /// </summary>
        /// <param name="subDirName">dll目录名称</param>
        public static AppStartup InitMEF(this AppStartup startup, string subDirName = "")
        {
            var catalog = new AggregateCatalog();

            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, subDirName ?? string.Empty);

            if (!Directory.Exists(path))
            {
                throw new ArgumentException("初始化MEF目录未找到");
            }

            catalog.Catalogs.Add(new DirectoryCatalog(path));

            var container = new CompositionContainer(catalog, true);

            EasyMefContainer.InitMefContainer(container);

            return(startup);
        }
Esempio n. 12
0
        /// <summary>
        /// 初始化MEF容器
        /// </summary>
        public static AppStartup InitMEF(this AppStartup startup, params Type[] typeList)
        {
            if (typeList == null || typeList.Length <= 0)
            {
                return(startup);
            }

            var typeDistinctList = typeList.Distinct();

            var catalog = new AggregateCatalog();

            foreach (var type in typeDistinctList)
            {
                catalog.Catalogs.Add(new TypeCatalog(type));
            }

            var container = new CompositionContainer(catalog, true);

            EasyMefContainer.InitMefContainer(container);

            return(startup);
        }
Esempio n. 13
0
        /// <summary>
        /// 初始化MEF容器
        /// </summary>
        public static AppStartup InitMEF(this AppStartup startup, params Assembly[] assemblyList)
        {
            if (assemblyList == null || assemblyList.Length <= 0)
            {
                return(startup);
            }

            var assemblyDistinctList = assemblyList.Distinct();

            var catalog = new AggregateCatalog();

            foreach (var assembly in assemblyDistinctList)
            {
                catalog.Catalogs.Add(new AssemblyCatalog(assembly));
            }

            var container = new CompositionContainer(catalog, true);

            EasyMefContainer.InitMefContainer(container);

            return(startup);
        }
Esempio n. 14
0
        public static void EasyConfigure(EasyConfigureReq req)
        {
            try
            {
                if (req.App == null)
                {
                    throw new Exception("IApplicationBuilder不能为空");
                }
                if (req.Env == null)
                {
                    throw new Exception("IWebHostEnvironment不能为空");
                }
                if (req.Configuration == null)
                {
                    throw new Exception("IConfiguration不能为空");
                }
                if (!req.WebType.IsInDefined())
                {
                    throw new Exception("WebType不合法");
                }

                if (req.Env.IsDevelopment())
                {
                    req.App.UseDeveloperExceptionPage();
                }

                if (!req.Env.IsDevelopment() && req.WebType == WebType.Mvc)
                {
                    string errorRedirect = req.Configuration?["appSettings:ErrorRedirect"];
                    errorRedirect = !string.IsNullOrWhiteSpace(errorRedirect) ? errorRedirect.Trim() : "/Home/Error";
                    req.App.UseExceptionHandler(errorRedirect);
                }

                if (req.IsHttpsRedirect)
                {
                    req.App.UseHttpsRedirection();
                }

                //配置中间件以转接 X-Forwarded-For 和 X-Forwarded-Proto 标头
                req.App.UseForwardedHeaders(new ForwardedHeadersOptions
                {
                    ForwardedHeaders = ForwardedHeaders.XForwardedFor |
                                       ForwardedHeaders.XForwardedProto
                });

                req.App.UseStaticFiles();
                req.App.UseRouting();

                if (string.IsNullOrWhiteSpace(req.CorsKey))
                {
                    req.App.UseCors();
                }
                else
                {
                    req.App.UseCors(req.CorsKey);
                }

                req.App.UseAuthentication();      //身份认证
                req.App.UseAuthorization();       //授权
                req.App.UseResponseCompression(); //添加gzip压缩中间件

                if (req.WebType == WebType.Mvc)
                {
                    req.App.UseEndpoints(endpoints =>
                    {
                        endpoints.MapControllerRoute(
                            name: "default",
                            pattern: req.MvcDefaultRoute?.Trim() ?? "{controller=Home}/{action=Index}/{id?}");
                    });
                }
                else if (req.WebType == WebType.WebApi)
                {
                    req.App.UseEndpoints(endpoints =>
                    {
                        endpoints.MapGet("/", async context =>
                        {
                            await context.Response.WriteAsync($"WebApi is OK! {req.WebApiName}");
                        });

                        endpoints.MapControllers();
                    });
                }

                var autofacContainer = req.App.ApplicationServices.GetAutofacRoot();
                var serviceLocator   = new AutofacServiceLocator(autofacContainer);
                EasyAutofac.Container      = autofacContainer;
                EasyAutofac.ServiceLocator = serviceLocator;

                var appStartup = new AppStartup()
                                 .InitIoC(serviceLocator)
                                 .CheckRedis();

                if (req.ConsulOption != null)
                {
                    appStartup.RegisterConsul(req.ConsulOption, req.App);
                }

                appStartup.Start();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "EasyConfigure出错");
                throw;
            }
        }