Esempio n. 1
0
        public static void AddMoz(this IServiceCollection services, Action <AppConfig> configure)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            services.Configure(configure);

            //获取配置
            var buildServiceProvider = services.BuildServiceProvider();
            var configuration        = buildServiceProvider.GetService <IConfiguration>();
            var webHostEnvironment   = buildServiceProvider.GetService <IWebHostEnvironment>();

            //验证appConfig
            var appConfig = buildServiceProvider.GetService <IOptions <AppConfig> >();

            if (appConfig?.Value == null)
            {
                throw new ArgumentNullException(nameof(AppConfig));
            }

            //必须配置EncryptKey
            if (appConfig.Value.AppSecret.IsNullOrEmpty())
            {
                throw new Exception(nameof(appConfig.Value.AppSecret));
            }

            //必须为16-32位
            if (appConfig.Value.AppSecret.Length < 16 || appConfig.Value.AppSecret.Length > 32)
            {
                throw new Exception("加密KEY位数不正确,必须为16-32位");
            }

            //检查是否已安装数据库
            DbFactory.CheckInstalled(appConfig.Value);

            var serviceProvider = ConfigureServices(services, configuration, webHostEnvironment, appConfig.Value);

            EngineContext.Create(serviceProvider);
        }
Esempio n. 2
0
        public static void AddMoz(this IServiceCollection services, Action <MozOptions> configure)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }

            if (configure == null)
            {
                throw new ArgumentNullException(nameof(configure));
            }

            services.Configure(configure);

            //获取配置
            var buildServiceProvider = services.BuildServiceProvider();
            var configuration        = buildServiceProvider.GetService <IConfiguration>();
            var webHostEnvironment   = buildServiceProvider.GetService <IWebHostEnvironment>();

            //验证mozOptions
            var options = buildServiceProvider.GetService <IOptions <MozOptions> >();

            if (options?.Value == null)
            {
                throw new Exception(nameof(MozOptions));
            }

            //必须配置EncryptKey
            if (options.Value.EncryptKey.IsNullOrEmpty())
            {
                throw new Exception(nameof(options.Value.EncryptKey));
            }

            //必须为16位
            if (options.Value.EncryptKey.Length != 16)
            {
                throw new Exception("加密KEY位数不正确,必须为16位");
            }

            //检查是否已安装数据库
            DbFactory.CheckInstalled(options.Value);

            var serviceProvider = ConfigureServices(services, configuration, webHostEnvironment, options.Value);

            EngineContext.Create(serviceProvider);
        }
        public static void UseMoz(this IApplicationBuilder application, IWebHostEnvironment env)
        {
            var configuration = application.ApplicationServices.GetService(typeof(IConfiguration)) as IConfiguration;
            var options       = (application.ApplicationServices.GetService(typeof(IOptions <AppConfig>)) as IOptions <AppConfig>)?.Value;

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (env.IsDevelopment())
            {
                application.UseDeveloperExceptionPage();
            }

            application.UseMiddleware <ErrorHandlingMiddleware>();


            application.UseStatusCodePages(async context =>
            {
                var registerType = options.StatusCodePageHandlerType;
                if (registerType != null && application.ApplicationServices.GetService(registerType) is IStatusCodePageHandler handler)
                {
                    await handler.Process(context);
                }
                else
                {
                    if (application.ApplicationServices.GetService(typeof(MozStatusCodePageHandler)) is IStatusCodePageHandler mozHandler)
                    {
                        await mozHandler.Process(context);
                    }
                }
            });



            application.UseMiddleware <JwtInHeaderMiddleware>();

            //定时任务
            if (DbFactory.CheckInstalled(options))
            {
                var taskScheduleManager = application.ApplicationServices.GetService(typeof(ITaskScheduleManager)) as ITaskScheduleManager;
                taskScheduleManager?.Init();
            }

            application.UseMozStaticFiles();

            application.UseAuthentication();

            application.UseSession();

            application.UseRouting();

            application.UseAuthorization();

            //获取所有的 IAppStartup,执行各个模块的启动类
            var startupConfigurations = TypeFinder.FindClassesOfType <IAppStartup>();
            var instances             = startupConfigurations
                                        .Select(startup => (IAppStartup)Activator.CreateInstance(startup.Type))
                                        .OrderBy(startup => startup?.Order);

            foreach (var instance in instances)
            {
                instance.Configure(application, configuration, env, options);
            }

            application.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("area", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });

            application.Run(context =>
            {
                context.Response.StatusCode = 404;
                return(Task.CompletedTask);
            });
        }
Esempio n. 4
0
        private static IServiceProvider ConfigureServices(IServiceCollection services, IConfiguration configuration,
                                                          IWebHostEnvironment webHostEnvironment, AppConfig mozOptions)
        {
            ServicePointManager.SecurityProtocol =
                SecurityProtocolType.Tls12 |
                SecurityProtocolType.Tls11 |
                SecurityProtocolType.Tls;

            services.AddAuthorization(options =>
            {
                options.AddPolicy("admin_authorize",
                                  policy => { policy.Requirements.Add(new DefaultAuthorizationRequirement("admin")); });
                options.AddPolicy("member_authorize",
                                  policy => { policy.Requirements.Add(new DefaultAuthorizationRequirement("member")); });
            });

            services.AddAuthentication()
            .AddJwtBearer(MozAuthAttribute.MozAuthorizeSchemes, cfg =>
            {
                cfg.RequireHttpsMetadata = false;
                cfg.SaveToken            = true;

                var parameters = EngineContext.Current.Resolve <IJwtService>().GetTokenValidationParameters();
                cfg.TokenValidationParameters = parameters;

                cfg.Events = new JwtBearerEvents
                {
                    //OnAuthenticationFailed = o => throw new AlertException("auth failure")
                };
            });

            //Session会话
            services.AddSession(options =>
            {
                options.Cookie.Name     = "__moz__session";
                options.Cookie.HttpOnly = true;
                options.IdleTimeout     = TimeSpan.FromMinutes(30);
            });

            //添加MVC
            services.AddMvc(options => { })
            .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; })
            .AddRazorRuntimeCompilation()
            .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; })
            .AddFluentValidation(options =>
            {
                options.ImplicitlyValidateChildProperties = true;
                options.ValidatorFactoryType = typeof(MozValidatorFactory);
                options.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
            });


            /*
             * services.AddApiVersioning(o =>
             * {
             *  o.ReportApiVersions = true;
             *  o.AssumeDefaultVersionWhenUnspecified = true;
             *  o.DefaultApiVersion = new ApiVersion(1, 0);
             * });
             */

            #region 依赖注入

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();
            services.AddTransient <IWorkContext, WebWorkContext>();
            services.AddSingleton <IFileUploader, LocalFileUploader>();
            services.AddTransient <HttpContextHelper>();
            services.AddSingleton <IEventPublisher, DefaultEventPublisher>();
            services.AddSingleton <ITaskScheduleManager, TaskScheduleManager>();
            services.AddSingleton <IAuthorizationHandler, DefaultAuthorizationHandler>();
            services.AddSingleton <IJobFactory, JobFactory>();
            services.AddTransient <FileStorageDataSource>();
            services.AddTransient <IFileManager, DefaultFileManager>();

            //注入服务类 查找所有Service结尾的类进行注册
            var allServiceInterfaces = TypeFinder.GetAllTypes()
                                       .Where(t => (t?.IsInterface ?? false) && !t.IsDefined <IgnoreRegisterAttribute>(false) &&
                                              t.TypeName.EndsWith("Service"));
            foreach (var serviceInterface in allServiceInterfaces)
            {
                var service = TypeFinder.FindClassesOfType(serviceInterface.Type)?.FirstOrDefault();
                if (service != null)
                {
                    services.AddTransient(serviceInterface.Type, service.Type);
                }
            }

            //注入所有Job类
            var jobTypes = TypeFinder.FindClassesOfType <IJob>().ToList();
            foreach (var jobType in jobTypes)
            {
                services.AddTransient(jobType.Type);
            }

            //注入所有Uploader类
            var uploaderTypes = TypeFinder.FindClassesOfType <IFileUploader>();
            foreach (var uploaderType in uploaderTypes)
            {
                services.AddTransient(uploaderType.Type);
            }

            //注册settings
            var settingTypes = TypeFinder.FindClassesOfType(typeof(ISettings)).ToList();
            foreach (var settingType in settingTypes)
            {
                services.TryAddTransient(settingType.Type, serviceProvider =>
                {
                    if (DbFactory.CheckInstalled(mozOptions))
                    {
                        var settingService = serviceProvider.GetService <ISettingService>();
                        return(settingService.LoadSetting(settingType.Type));
                    }

                    var instance = Activator.CreateInstance(settingType.Type);
                    return(instance);
                });
            }

            //注入 ExceptionHandler
            var exceptionHandlers = TypeFinder.FindClassesOfType(typeof(IExceptionHandler))
                                    .Where(it => it.Type != typeof(ErrorHandlingMiddleware))
                                    .ToList();
            foreach (var exceptionHandler in exceptionHandlers)
            {
                services.AddSingleton(exceptionHandler.Type);
            }

            //注入 StatusCodePageHandler
            var statusCodePageHandlers = TypeFinder.FindClassesOfType(typeof(IStatusCodePageHandler)).ToList();
            foreach (var statusCodePageHandler in statusCodePageHandlers)
            {
                services.AddSingleton(statusCodePageHandler.Type);
            }

            //事件发布
            var consumerTypes = TypeFinder.FindClassesOfType(typeof(ISubscriber <>)).ToList();
            foreach (var consumerType in consumerTypes)
            {
                var interfaceTypes = consumerType.Type.FindInterfaces((type, criteria) =>
                {
                    var isMatch = type.IsGenericType &&
                                  ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                    return(isMatch);
                }, typeof(ISubscriber <>));
                var interfaceType = interfaceTypes.FirstOrDefault();
                if (interfaceType != null)
                {
                    services.AddTransient(interfaceType, consumerType.Type);
                }
            }

            #endregion

            //获取所有的 IAppStartup
            var startupConfigurations = TypeFinder.FindClassesOfType <IAppStartup>();

            //添加嵌入cshtml资源
            services.Configure <MvcRazorRuntimeCompilationOptions>(options =>
            {
                foreach (var cfg in startupConfigurations)
                {
                    options.FileProviders.Add(new EmbeddedFileProvider(cfg.Type.GetTypeInfo().Assembly));
                }
            });

            //执行各个模块的启动类
            var instances = startupConfigurations
                            .Select(startup => (IAppStartup)Activator.CreateInstance(startup.Type))
                            .OrderBy(startup => startup.Order);
            foreach (var instance in instances)
            {
                instance.ConfigureServices(services, configuration, webHostEnvironment, mozOptions);
            }

            //services.
            return(services.BuildServiceProvider());
        }