public string LoadOrg()
        {
            var orgs = AutofacExt.GetFromFac <LoginApp>().GetLoginUser().AccessedOrgs.MapToList <Org>();

            //添加根节点
            orgs.Add(new Org
            {
                Id        = 0,
                ParentId  = -1,
                Name      = "根结点",
                CascadeId = "0"
            });
            return(JsonHelper.Instance.Serialize(orgs));
        }
        public string LoadModuleWithRoot()
        {
            var orgs = AutofacExt.GetFromFac <LoginApp>().GetLoginUser().Modules.MapToList <ModuleView>();

            //添加根节点
            orgs.Add(new Module
            {
                Id        = 0,
                ParentId  = -1,
                Name      = "根节点",
                CascadeId = "0"
            });
            return(JsonHelper.Instance.Serialize(orgs));
        }
Ejemplo n.º 3
0
        public void Init()
        {
            var serviceCollection = GetService();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddOptions();

            serviceCollection.AddDbContext <OpenAuthDBContext>(options =>
                                                               options.UseSqlServer("Data Source=.;Initial Catalog=OpenAuthDB;User=sa;Password=000000;Integrated Security=True"));

            var container = AutofacExt.InitAutofac(serviceCollection);

            _autofacServiceProvider = new AutofacServiceProvider(container);
        }
Ejemplo n.º 4
0
        public void Init()
        {
            var serviceCollection = GetService();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddOptions();

            serviceCollection.AddDbContext <XgossContext>(options =>
                                                          options.UseSqlServer("Data Source=117.27.89.185,60012;Database=xgoss_netcore;Uid=sa;Pwd=Dongri_123456"));

            var container = AutofacExt.InitAutofac(serviceCollection);

            _autofacServiceProvider = new AutofacServiceProvider(container);
        }
Ejemplo n.º 5
0
        public string UserRegister(Customer view)
        {
            CustomerApplication app = AutofacExt.GetFromFac <CustomerApplication>();

            Infrastructure.Response result = new Infrastructure.Response();
            try
            {
                app.Add(view);
            }
            catch (Exception ex)
            {
                result.Status  = false;
                result.Message = ex.Message;
            }
            return(JsonHelper.Instance.Serialize(result));
        }
Ejemplo n.º 6
0
        public string IsCustomerNameExist(string custName)
        {
            CustomerApplication app = AutofacExt.GetFromFac <CustomerApplication>();

            Infrastructure.Response result = new Infrastructure.Response();
            try
            {
                result.Message = app.IsCustomerNameExist(custName).ToString();
            }
            catch (Exception ex)
            {
                result.Status  = false;
                result.Message = ex.Message;
            }
            return(JsonHelper.Instance.Serialize(result));
        }
Ejemplo n.º 7
0
        public void Init()
        {
            var serviceCollection = GetService();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddOptions();
            //读取OpenAuth.WebApi的配置文件用于单元测试
            var            path     = AppContext.BaseDirectory;
            int            pos      = path.IndexOf("OpenAuth.App");
            var            basepath = Path.Combine(path.Substring(0, pos), "OpenAuth.WebApi");
            IConfiguration config   = new ConfigurationBuilder()
                                      .SetBasePath(basepath)
                                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                      .AddJsonFile("appsettings.Development.json", optional: true)
                                      .AddEnvironmentVariables()
                                      .Build();

            serviceCollection.Configure <AppSetting>(config.GetSection("AppSetting"));
            //添加log4net
            serviceCollection.AddLogging(builder =>
            {
                builder.ClearProviders();                               //去掉默认的日志
                builder.AddConfiguration(config.GetSection("Logging")); //读取配置文件中的Logging配置
                builder.AddLog4Net();
            });
            //注入OpenAuth.WebApi配置文件
            serviceCollection.AddScoped(x => config);

            //模拟HTTP请求
            var httpContextAccessorMock = new Mock <IHttpContextAccessor>();

            httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TOKEN_NAME]).Returns("tokentest");
            httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TENANT_ID]).Returns("OpenAuthDBContext");
            serviceCollection.AddScoped(x => httpContextAccessorMock.Object);

            serviceCollection.AddDbContext <OpenAuthDBContext>();

            var container = AutofacExt.InitForTest(serviceCollection);

            _autofacServiceProvider = new AutofacServiceProvider(container);
            AutofacContainerModule.ConfigServiceProvider(_autofacServiceProvider);

            var dbtypes = config.GetSection("AppSetting:DbTypes").GetChildren()
                          .ToDictionary(x => x.Key, x => x.Value);

            Console.WriteLine($"单元测试数据库信息:{dbtypes[httpContextAccessorMock.Object.GetTenantId()]}/{config.GetSection("ConnectionStrings")["OpenAuthDBContext"]}");
        }
Ejemplo n.º 8
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            var description =
                (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)filterContext.ActionDescriptor;

            Controllername = description.ControllerName.ToLower();
            Actionname     = description.ActionName.ToLower();

            var config  = AutofacExt.GetFromFac <IOptions <AppSetting> >();
            var version = config.Value.Version;

            if (version == "demo" && Request.Method == "POST")
            {
                filterContext.Result = new RedirectResult("/Error/Demo");
                return;
                // throw new Exception("演示版本,不要乱动,当前模块:" + Controllername + "/" + Actionname);
            }

            if (!_authUtil.CheckLogin())
            {
                return;
            }

            var function = ((TypeInfo)GetType()).DeclaredMethods.FirstOrDefault(u => u.Name.ToLower() == Actionname);

            if (function == null)
            {
                throw new Exception("未能找到Action");
            }
            //权限验证标识
            var authorize = function.GetCustomAttribute(typeof(AuthenticateAttribute));

            if (authorize == null)
            {
                return;
            }
            var currentModule = _authUtil.GetCurrentUser().Modules.FirstOrDefault(u => u.Url.ToLower().Contains(Controllername));

            //当前登录用户没有Action记录&&Action有authenticate标识
            if (currentModule == null)
            {
                filterContext.Result = new RedirectResult("/Login/Index");
                return;
            }
        }
Ejemplo n.º 9
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            services.AddSession(options =>
            {
                options.Cookie.HttpOnly = true;
            });
            services.AddMemoryCache();
            services.AddOptions();
            services.Configure <SiteConfig>(Configuration.GetSection("SiteConfig"));
            services.AddLogging();
            services.AddCloudscribePagination();
            services.AddResponseCompression();
            services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>());
            services.AddMiniProfiler().AddEntityFramework();
            services.AddMvc(cfg =>
            {
                cfg.Filters.Add(typeof(ExceptionAttribute));//异常捕获
            });
            services.AddMvc(cfg =>
            {
                cfg.Filters.Add(typeof(MvcMenuFilter));
            });

            services.AddHangfire(x =>
            {
                var connectionString = Configuration["Data:Redis:ConnectionString"];
                x.UseRedisStorage(connectionString, new Hangfire.Redis.RedisStorageOptions()
                {
                    Db = 10
                });
            });


            #region mysql
            ////services.AddHangfire(x => x.UseStorage(new MySqlStorage(Configuration["Hangfire:ConStr"]
            ////    ,
            ////       new MySqlStorageOptions
            ////       {
            ////           QueuePollInterval = TimeSpan.FromSeconds(600)            //- 作业队列轮询间隔。默认值为15秒。
            ////       }
            ////    )));
            #endregion
            services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"]));
            return(new AutofacServiceProvider(AutofacExt.InitAutofac(services)));
        }
Ejemplo n.º 10
0
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var loginUser = AutofacExt.GetFromFac <LoginApp>().GetLoginUser();

            if (!User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("/Login/Index");
                return;
            }
            var controllername = Request.RequestContext.RouteData.Values["controller"].ToString().ToLower();
            var actionname     = filterContext.ActionDescriptor.ActionName.ToLower();

            var function = this.GetType().GetMethods().FirstOrDefault(u => u.Name.ToLower() == actionname);

            if (function == null)
            {
                throw new Exception("未能找到Action");
            }

            var anonymous = function.GetCustomAttribute(typeof(AnonymousAttribute));
            var module    = loginUser.Modules.FirstOrDefault(u => u.Url.ToLower().Contains(controllername));

            //当前登录用户没有Action记录&&Action没有anonymous标识
            if (module == null && anonymous == null)
            {
                filterContext.Result = new RedirectResult("/Login/Index");
                return;
            }
            else
            {
                ViewBag.Module = module;  //为View显示服务,主要是为了显示按钮
            }

            var version = ConfigurationManager.AppSettings["version"];

            if (version == "demo")
            {
                HttpPostAttribute hobbyAttr = (HttpPostAttribute)Attribute.GetCustomAttribute(function, typeof(HttpPostAttribute));
                if (actionname.Contains("del") || hobbyAttr != null)  //客户端提交数据
                {
                    throw new HttpException(400, "演示版本,不能进行该操作,当前模块:" + controllername + "/" + actionname);
                }
            }

            base.OnActionExecuting(filterContext);
        }
Ejemplo n.º 11
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //services.AddIdentity<ApplicationUser, Role>().AddUserStore<CustomUserStore>()
            //    .AddDefaultTokenProviders();
            //services.AddTransient<IRoleStore<Role>, CustomRoleStore>();

            var builder = services.AddIdentityServer()
                          .AddInMemoryIdentityResources(Config.GetIdentityResources())
                          .AddInMemoryApiResources(Config.GetApis())
                          .AddInMemoryClients(Config.GetClients(Environment.IsProduction()))
                          .AddProfileService <CustomProfileService>();

            services.AddCors();

            //全部用测试环境,正式环境请参考https://www.cnblogs.com/guolianyu/p/9872661.html
            //if (Environment.IsDevelopment())
            //{
            builder.AddDeveloperSigningCredential();
            //}
            //else
            //{
            //    throw new Exception("need to configure key material");
            //}

            services.Configure <AppSetting>(Configuration.GetSection("AppSetting"));
            services.AddMvc().AddControllersAsServices().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMemoryCache();
            services.AddCors();
            //在startup里面只能通过这种方式获取到appsettings里面的值,不能用IOptions😰
            var dbType = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbType")).Value;

            if (dbType == Define.DBTYPE_SQLSERVER)
            {
                services.AddDbContext <OpenAuthDBContext>(options =>
                                                          options.UseSqlServer(Configuration.GetConnectionString("OpenAuthDBContext")));
            }
            else  //mysql
            {
                services.AddDbContext <OpenAuthDBContext>(options =>
                                                          options.UseMySql(Configuration.GetConnectionString("OpenAuthDBContext")));
            }

            return(new AutofacServiceProvider(AutofacExt.InitAutofac(services)));
        }
Ejemplo n.º 12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Application_Start(object sender, EventArgs e)
        {
            //  DbInitService.Init();
            AutoMapperConfiguration.ConfigExt();
            AutofacExt.InitAutofac();
            // Log.Info("log", "Application_Start:" + DateTime.Now.ToString()); // 在应用程序启动时运行的代码
            AreaRegistration.RegisterAllAreas();

            GlobalConfiguration.Configure(WebApiConfig.Register);

            RouteTable.Routes.Ignore(""); //Allow index.html to load
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            //取消注释默认返回 json
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();

            JobManager.Initialize(new TaskTime());
        }
Ejemplo n.º 13
0
        public void Init()
        {
            var serviceCollection = GetService();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddOptions();

            // 测试my sql
            // serviceCollection.AddDbContext<OpenAuthDBContext>(options =>
            //     options.UseMySql("server=127.0.0.1;user id=root;database=openauthdb;password=000000"));

            serviceCollection.AddDbContext <OpenAuthDBContext>(options =>
                                                               options.UseSqlServer("Data Source=.;Initial Catalog=OpenAuthDB;User=sa;Password=000000;Integrated Security=True"));

            var container = AutofacExt.InitForTest(serviceCollection);

            _autofacServiceProvider = new AutofacServiceProvider(container);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 获取所有章节到本地
        /// </summary>
        /// <param name="novelId"></param>
        /// <returns></returns>
        public string GetAllChapterToLocal(string novelId)
        {
            try
            {
                var novel       = _novelManagerApp.GetNovel(novelId);
                var sqlStr      = string.Format("Select * From [{0}] Where state <> 2 ", novelId);
                var listChapter = _app.Repository.ChapterQueryFromSql(sqlStr).ToList();
                if (listChapter.Count() > 0)
                {
                    ThreadPool.QueueUserWorkItem(x =>
                    {
                        var _chapterManagerApp = AutofacExt.GetFromFac <ChapterManagerApp>();

                        foreach (var chapter in listChapter)
                        {
                            _chapterManagerApp.UpdateChapterState(novel.Id, chapter.Id, 1);
                            var tmpChapterContent = _chapterManagerApp.GetWebChapterContent(chapter);
                            _chapterManagerApp.SaveToLocal(_hostingEnvironment.ContentRootPath, novel, chapter, tmpChapterContent);
                            _chapterManagerApp.UpdateChapterState(novel.Id, chapter.Id, 2);
                        }

                        if (_chapterManagerApp.IsAllChapterToLocal(novel.Id))
                        {
                            novel.State          = 2;
                            var _novelManagerApp = AutofacExt.GetFromFac <NovelManagerApp>();
                            _novelManagerApp.Update(novel);
                        }
                    });
                }
                else
                {
                    Result.Code    = 500;
                    Result.Message = "未找到要获取的章节或者章节全部获取完成!";
                }
            }
            catch (Exception ex)

            {
                Result.Code    = 500;
                Result.Message = ex.ToString();
            }
            return(JsonHelper.Instance.Serialize(Result));
        }
Ejemplo n.º 15
0
        public void Init()
        {
            var serviceCollection = GetService();

            serviceCollection.AddMemoryCache();
            serviceCollection.AddOptions();
            //讀取OpenAuth.WebApi的配置檔案用於單元測試
            var            path     = AppContext.BaseDirectory;
            int            pos      = path.IndexOf("OpenAuth.App");
            var            basepath = Path.Combine(path.Substring(0, pos), "OpenAuth.WebApi");
            IConfiguration config   = new ConfigurationBuilder()
                                      .SetBasePath(basepath)
                                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                      .AddJsonFile("appsettings.Development.json", optional: true)
                                      .AddEnvironmentVariables()
                                      .Build();

            Console.WriteLine($"單元測試資料庫資訊:{config.GetSection("AppSetting")["DbType"]}/{config.GetSection("ConnectionStrings")["OpenAuthDBContext"]}");

            //新增log4net
            serviceCollection.AddLogging(builder =>
            {
                builder.ClearProviders();                               //去掉預設的日誌
                builder.AddConfiguration(config.GetSection("Logging")); //讀取配置檔案中的Logging配置
                builder.AddLog4Net();
            });
            //注入OpenAuth.WebApi配置檔案
            serviceCollection.AddScoped(x => config);

            //模擬HTTP請求
            var httpContextAccessorMock = new Mock <IHttpContextAccessor>();

            httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TOKEN_NAME]).Returns("tokentest");
            httpContextAccessorMock.Setup(x => x.HttpContext.Request.Query[Define.TENANT_ID]).Returns("OpenAuthDBContext");
            serviceCollection.AddScoped(x => httpContextAccessorMock.Object);

            serviceCollection.AddDbContext <OpenAuthDBContext>();

            var container = AutofacExt.InitForTest(serviceCollection);

            _autofacServiceProvider = new AutofacServiceProvider(container);
            AutofacContainerModule.ConfigServiceProvider(_autofacServiceProvider);
        }
Ejemplo n.º 16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;//为 True 时获取不到 Session 的值
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDistributedMemoryCache();
            //添加Session 服务
            services.AddSession(options =>
            {
                options.IdleTimeout     = TimeSpan.FromMinutes(60);
                options.Cookie.HttpOnly = true;
            });

            services.AddHttpContextHelperAccessor();
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                //options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            //设置认证cookie名称、过期时间、是否允许客户端读取
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.Cookie.Name       = "nkblog";              //cookie名称
                options.Cookie.Expiration = TimeSpan.FromHours(1); //过期时间
                options.Cookie.HttpOnly   = true;                  //不允许客户端获取
                options.SlidingExpiration = true;                  // 是否在过期时间过半的时候,自动延期
            });
            //Redis.Initialization();
            return(new AutofacServiceProvider(AutofacExt.InitAutofac(services)));
        }
Ejemplo n.º 17
0
 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     //启用MemoryCache
     services.AddMemoryCache();
     //设置MemoryCache缓存有效时间为5分钟。
     services.Configure <MemoryCacheEntryOptions>(
         options => options.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));
     //跨域
     services.AddCors();
     //配置DBConctext
     services.AddDbContext <VDbContext>(options =>
     {
         options.EnableSensitiveDataLogging(true);
         options.UseSqlServer(Configuration.GetConnectionString("VDbContext"));
     });
     //记录日志
     services.AddMvc(option => { option.Filters.Add(new GlobalExceptionFilter()); })
     .AddControllersAsServices();
     return(new AutofacServiceProvider(AutofacExt.InitAutofac(services)));
 }
Ejemplo n.º 18
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();
            services.AddOptions();
            services.Configure <SiteConfig>(Configuration.GetSection("SiteConfig"));
            services.AddLogging();
            services.AddResponseCompression();
            services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>());
            services.AddHangfire(x =>
            {
                var connectionString = Configuration["Data:Redis:ConnectionString"];
                x.UseRedisStorage(connectionString, new RedisStorageOptions()
                {
                    Db = int.Parse(Configuration["Data:Redis:Db"])
                });
            });

            #region mysql
            //services.AddHangfire(x => x.UseStorage(new MySqlStorage(
            // Configuration["Hangfire:ConStr"],
            //    new MySqlStorageOptions
            //    {
            //        TransactionIsolationLevel = IsolationLevel.ReadCommitted, // 事务隔离级别。默认是读取已提交。
            //        QueuePollInterval = TimeSpan.FromSeconds(15),             //- 作业队列轮询间隔。默认值为15秒。
            //        JobExpirationCheckInterval = TimeSpan.FromHours(1),       //- 作业到期检查间隔(管理过期记录)。默认值为1小时。
            //        CountersAggregateInterval = TimeSpan.FromMinutes(5),      //- 聚合计数器的间隔。默认为5分钟。
            //        PrepareSchemaIfNecessary = true,                          //- 如果设置为true,则创建数据库表。默认是true。
            //        DashboardJobListLimit = 50000,                            //- 仪表板作业列表限制。默认值为50000。
            //        TransactionTimeout = TimeSpan.FromMinutes(1),             //- 交易超时。默认为1分钟。
            //        TablePrefix = "Hangfire"                                  //- 数据库中表的前缀。默认为none
            //    }
            //    )));
            #endregion

            services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"]));
            var container = AutofacExt.InitAutofac(services);
            // GlobalConfiguration.Configuration.UseAutofacActivator(container);
            return(new AutofacServiceProvider(container));
        }
Ejemplo n.º 19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddSwaggerGen(option =>
            {
                option.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Version     = "v1",
                    Title       = " SharePlatform.WebApi",
                    Description = "by SharePlatform"
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                option.IncludeXmlComments(xmlPath);
                option.OperationFilter <GlobalHttpHeaderOperationFilter>(); // 添加httpHeader参数
            });
            services.AddMvc().AddControllersAsServices().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddMemoryCache();
            services.AddCors();
            //在startup里面只能通过这种方式获取到appsettings里面的值,不能用IOptions😰
            var dbType = ((ConfigurationSection)Configuration.GetSection("AppSetting:DbType")).Value;

            if (dbType == Define.DBTYPE_SQLSERVER)
            {
                services.AddDbContext <SharePlatformDBContext>(options =>
                                                               options.UseSqlServer(Configuration.GetConnectionString("SharePlatformDBContext")));
            }
            else  //mysql
            {
                services.AddDbContext <SharePlatformDBContext>(options =>
                                                               options.UseMySql(Configuration.GetConnectionString("SharePlatformDBContext")));
            }


            return(new AutofacServiceProvider(AutofacExt.InitAutofac(services)));
        }
Ejemplo n.º 20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            var connStr      = Configuration.GetConnectionString("MySqlConn");
            var assemblyName = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


            services.AddDbContext <LBDDBContext>(option =>
            {
                option.UseMySql(connStr, b => b.MigrationsAssembly(assemblyName));
            });

            services.AddMvc(option =>
            {
                option.Filters.Add <AuthFilter>();
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            return(new AutofacServiceProvider(AutofacExt.InitAutofac(services)));
        }
Ejemplo n.º 21
0
        protected void Application_Start()
        {
            AutofacExt.Init();

            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
Ejemplo n.º 22
0
 public StockManagerController()
 {
     _app = AutofacExt.GetFromFac <StockManagerApp>();
 }
 public CategoryManagerController()
 {
     _app = AutofacExt.GetFromFac <CategoryManagerApp>();
 }
Ejemplo n.º 24
0
 public void ConfigureContainer(ContainerBuilder builder)
 {
     AutofacExt.InitAutofac(builder);
 }
Ejemplo n.º 25
0
 public HomeController()
 {
     _app = AutofacExt.GetFromFac <ModuleManagerApp>();
 }
Ejemplo n.º 26
0
 public TestBase()
 {
     AutofacExt.InitDI();
 }
Ejemplo n.º 27
0
 public OrderCatchController()
 {
     _app = AutofacExt.GetFromFac <OrderCatchApp>();
 }
Ejemplo n.º 28
0
 public OrderApproveController()
 {
     _app = AutofacExt.GetFromFac <CustomerApp>();
 }
 public RelevanceManagerController()
 {
     _app = AutofacExt.GetFromFac <RevelanceManagerApp>();
 }
Ejemplo n.º 30
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            if (bool.Parse(Configuration["IsIdentity"]))
            {
                System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

                services.AddAuthentication(options =>
                {
                    options.DefaultScheme          = "Cookies";
                    options.DefaultChallengeScheme = "oidc";
                })
                .AddCookie("Cookies")
                .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority            = Configuration["IdentityUrl"];
                    options.RequireHttpsMetadata = false;

                    options.ClientId   = "CompanyName.ProjectName.Mvc";
                    options.SaveTokens = true;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        NameClaimType = "name",
                        RoleClaimType = "role",
                    };
                });
            }
            else
            {
                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
            }

            services.AddSession(options =>
            {
                options.Cookie.HttpOnly = true;
            });
            services.AddMemoryCache();
            services.AddOptions();
            services.Configure <SiteConfig>(Configuration.GetSection("SiteConfig"));
            services.AddLogging();
            services.AddCloudscribePagination();
            services.AddResponseCompression();
            services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>());
            if (bool.Parse(Configuration["IsUseMiniProfiler"]))
            {
                services.AddMiniProfiler().AddEntityFramework();
            }

            services.AddMvc(cfg =>
            {
                cfg.Filters.Add(typeof(ExceptionAttribute));//异常捕获
            });
            services.AddMvc(cfg =>
            {
                cfg.Filters.Add(typeof(MvcMenuFilter));
            });
            services.AddHangfire(x =>
            {
                var connectionString = Configuration["Data:Redis:ConnectionString"];
                x.UseRedisStorage(connectionString, new Hangfire.Redis.RedisStorageOptions()
                {
                    Db = int.Parse(Configuration["Data:Redis:Db"])
                });
            });
            services.AddDbContext <EFCoreDBContext>(options => options.UseMySql(Configuration["Data:MyCat:ConnectionString"]));
            return(new AutofacServiceProvider(AutofacExt.InitAutofac(services, Assembly.GetExecutingAssembly())));
        }