public static T CreateApi <T>(string dataseed, string usercode) where T : BaseApiController, new() { var _controller = new T(); _controller.DC = new DataContext(dataseed, DBTypeEnum.Memory); Mock <HttpContext> mockHttpContext = new Mock <HttpContext>(); MockHttpSession mockSession = new MockHttpSession(); mockHttpContext.Setup(s => s.Session).Returns(mockSession); Mock <IServiceProvider> mockService = new Mock <IServiceProvider>(); mockService.Setup(x => x.GetService(typeof(GlobalData))).Returns(new GlobalData()); mockService.Setup(x => x.GetService(typeof(Configs))).Returns(new Configs()); mockService.Setup(x => x.GetService(typeof(IDistributedCache))).Returns(new MemoryDistributedCache(Options.Create <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions()))); GlobalServices.SetServiceProvider(mockService.Object); _controller.ControllerContext.HttpContext = mockHttpContext.Object; _controller.Cache = new MemoryDistributedCache(Options.Create <MemoryDistributedCacheOptions>(new MemoryDistributedCacheOptions())); _controller.LoginUserInfo = new LoginUserInfo { ITCode = usercode ?? "user" }; _controller.ConfigInfo = new Configs(); _controller.GlobaInfo = new GlobalData(); _controller.GlobaInfo.AllAccessUrls = new List <string>(); _controller.GlobaInfo.AllAssembly = new List <System.Reflection.Assembly>(); _controller.GlobaInfo.AllModels = new List <Type>(); _controller.GlobaInfo.SetModuleGetFunc(() => new List <FrameworkModule>()); return(_controller); }
public BaseCRUDVMTestTop() { _seed = Guid.NewGuid().ToString(); _schoolvm.DC = new DataContext(_seed, DBTypeEnum.Memory); _majorvm.DC = new DataContext(_seed, DBTypeEnum.Memory); _studentvm.DC = new DataContext(_seed, DBTypeEnum.Memory); _schoolvm.Session = new MockSession(); _majorvm.Session = new MockSession(); _studentvm.Session = new MockSession(); _schoolvm.MSD = new MockMSD(); _majorvm.MSD = new MockMSD(); _studentvm.MSD = new MockMSD(); _schoolvm.LoginUserInfo = new LoginUserInfo { ITCode = "schooluser" }; _majorvm.LoginUserInfo = new LoginUserInfo { ITCode = "majoruser" }; _studentvm.LoginUserInfo = new LoginUserInfo { ITCode = "studentuser" }; Mock <IServiceProvider> mockService = new Mock <IServiceProvider>(); mockService.Setup(x => x.GetService(typeof(GlobalData))).Returns(new GlobalData()); mockService.Setup(x => x.GetService(typeof(Configs))).Returns(new Configs()); GlobalServices.SetServiceProvider(mockService.Object); }
public static T CreateController <T>(string dataseed, string usercode) where T : BaseController, new() { var _controller = new T(); _controller.DC = new FrameworkContext(dataseed, DBTypeEnum.Memory); Mock <HttpContext> mockHttpContext = new Mock <HttpContext>(); MockHttpSession mockSession = new MockHttpSession(); mockHttpContext.Setup(s => s.Session).Returns(mockSession); mockHttpContext.Setup(x => x.Request).Returns(new DefaultHttpRequest(new DefaultHttpContext())); Mock <IServiceProvider> mockService = new Mock <IServiceProvider>(); mockService.Setup(x => x.GetService(typeof(GlobalData))).Returns(new GlobalData()); mockService.Setup(x => x.GetService(typeof(Configs))).Returns(new Configs()); GlobalServices.SetServiceProvider(mockService.Object); _controller.ControllerContext.HttpContext = mockHttpContext.Object; _controller.LoginUserInfo = new LoginUserInfo { ITCode = usercode ?? "user" }; _controller.ConfigInfo = new Configs(); _controller.GlobaInfo = new GlobalData(); _controller.GlobaInfo.AllAccessUrls = new List <string>(); _controller.GlobaInfo.AllAssembly = new List <System.Reflection.Assembly>(); _controller.GlobaInfo.AllModels = new List <Type>(); _controller.GlobaInfo.AllModule = new List <FrameworkModule>(); _controller.UIService = new LayuiUIService(); return(_controller); }
public static IServiceCollection AddFrameworkService(this IServiceCollection services, Func <ActionExecutingContext, string> CsSector = null, List <IDataPrivilege> dataPrivilegeSettings = null) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .Build(); services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = ".WalkingTec.Session"; options.IdleTimeout = TimeSpan.FromSeconds(3600); }); var gd = GetGlobalData(); services.AddSingleton(gd); var con = config.Get <Configs>() ?? new Configs(); if (dataPrivilegeSettings != null) { con.DataPrivilegeSettings = dataPrivilegeSettings; } else { con.DataPrivilegeSettings = new List <IDataPrivilege>(); } services.AddSingleton(con); services.AddMvc(options => { options.Filters.Add(new DataContextFilter(CsSector)); options.Filters.Add(new PrivilegeFilter()); options.Filters.Add(new FrameworkFilter()); }) .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.Configure <RazorViewEngineOptions>(options => { options.FileProviders.Add( new EmbeddedFileProvider( typeof(_CodeGenController).GetTypeInfo().Assembly, "WalkingTec.Mvvm.Mvc" // your external assembly's base namespace ) ); var admin = GetRuntimeAssembly("WalkingTec.Mvvm.Mvc.Admin"); if (admin != null) { options.FileProviders.Add( new EmbeddedFileProvider( admin, "WalkingTec.Mvvm.Mvc.Admin" // your external assembly's base namespace ) ); } }); services.AddSingleton <IUIService, DefaultUIService>(); GlobalServices.SetServiceProvider(services.BuildServiceProvider()); return(services); }
public static IServiceCollection AddLayui(this IServiceCollection services) { services.Remove(new ServiceDescriptor(typeof(IUIService), typeof(DefaultUIService), ServiceLifetime.Singleton)); services.AddSingleton <IUIService, LayuiUIService>(); GlobalServices.SetServiceProvider(services.BuildServiceProvider()); return(services); }
public BaseVMTest() { _vm = new BaseVM(); Mock <IServiceProvider> mockService = new Mock <IServiceProvider>(); mockService.Setup(x => x.GetService(typeof(GlobalData))).Returns(new GlobalData()); mockService.Setup(x => x.GetService(typeof(Configs))).Returns(new Configs()); GlobalServices.SetServiceProvider(mockService.Object); }
/// <summary> /// Add SnowLeopard Autofac /// </summary> /// <param name="services"></param> public static IServiceProvider AddSnowLeopardAutofac(this IServiceCollection services) { var builder = new ContainerBuilder(); builder.Populate(services); var serviceProvider = new AutofacServiceProvider(builder.Build()); GlobalServices.SetServiceProvider(serviceProvider); return(serviceProvider); }
static void RegisterServices() { var configurationBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); var hostingConfig = configurationBuilder.Build(); var services = new ServiceCollection(); services.AddSnowLeopardRedis(hostingConfig); services.AddSnowLeopardServices(); var container = new ContainerBuilder(); container.Populate(services); GlobalServices.SetServiceProvider(new AutofacServiceProvider(container.Build())); }
public BasePaedListVMTest() { Mock <IServiceProvider> mockService = new Mock <IServiceProvider>(); mockService.Setup(x => x.GetService(typeof(GlobalData))).Returns(new GlobalData()); mockService.Setup(x => x.GetService(typeof(Configs))).Returns(new Configs()); GlobalServices.SetServiceProvider(mockService.Object); _seed = Guid.NewGuid().ToString(); _studentListVM = new BasePagedListVM <Student, BaseSearcher>(); _studentListVM.DC = new DataContext(_seed, DBTypeEnum.Memory); for (int i = 1; i <= 20; i++) { _studentListVM.DC.Set <Student>().Add(new Student { LoginName = "s" + i.ToString("00"), Password = "******", Name = "n" + (int)(i / 10), IsValid = true }); } _studentListVM.DC.SaveChanges(); }
public static IServiceCollection AddFrameworkService(this IServiceCollection services, Func <ActionExecutingContext, string> CsSector = null, List <IDataPrivilege> dataPrivilegeSettings = null, WebHostBuilderContext webHostBuilderContext = null ) { CurrentDirectoryHelpers.SetCurrentDirectory(); var configBuilder = new ConfigurationBuilder(); if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"))) { var binLocation = Assembly.GetEntryAssembly()?.Location; if (!string.IsNullOrEmpty(binLocation)) { var binPath = new FileInfo(binLocation).Directory?.FullName; if (File.Exists(Path.Combine(binPath, "appsettings.json"))) { Directory.SetCurrentDirectory(binPath); configBuilder.SetBasePath(binPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); } } } else { configBuilder.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); } if (webHostBuilderContext != null) { var env = webHostBuilderContext.HostingEnvironment; configBuilder .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); } var config = configBuilder.Build(); services.AddLocalization(options => options.ResourcesPath = "Resources"); var gd = GetGlobalData(); var con = config.Get <Configs>() ?? new Configs(); //services.Configure<Configs>(config); if (dataPrivilegeSettings != null) { con.DataPrivilegeSettings = dataPrivilegeSettings; } else { con.DataPrivilegeSettings = new List <IDataPrivilege>(); } SetDbContextCI(gd.AllAssembly, con); gd.AllModels = GetAllModels(con); services.AddSingleton(gd); services.AddSingleton(con); services.AddResponseCaching(); services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = con.CookiePre + ".Session"; options.IdleTimeout = TimeSpan.FromSeconds(3600); }); SetupDFS(con); services.AddCors(options => { if (con.CorsOptions?.Policy?.Count > 0) { foreach (var item in con.CorsOptions.Policy) { string[] domains = item.Domain?.Split(','); options.AddPolicy(item.Name, builder => { builder.WithOrigins(domains) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); } } else { options.AddPolicy("_donotusedefault", builder => { builder.WithOrigins("http://localhost", "https://localhost") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); } }); // edit start by @vito services.TryAdd(ServiceDescriptor.Transient <IAuthorizationService, WTMAuthorizationService>()); services.TryAdd(ServiceDescriptor.Transient <IPolicyEvaluator, Core.Auth.PolicyEvaluator>()); services.TryAddEnumerable( ServiceDescriptor.Transient <IApplicationModelProvider, Core.Auth.AuthorizationApplicationModelProvider>()); // edit end var mvc = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.dll").FirstOrDefault(); var admin = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.Admin.dll").FirstOrDefault(); //set Core's _Callerlocalizer to use localizer point to the EntryAssembly's Program class var programType = Assembly.GetEntryAssembly().GetTypes().Where(x => x.Name == "Program").FirstOrDefault(); var coredll = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Core.dll").FirstOrDefault(); var programLocalizer = new ResourceManagerStringLocalizerFactory( Options.Create( new LocalizationOptions { ResourcesPath = "Resources" }) , new Microsoft.Extensions.Logging.LoggerFactory() ) .Create(programType); coredll.GetType("WalkingTec.Mvvm.Core.Program").GetProperty("_Callerlocalizer").SetValue(null, programLocalizer); services.AddMvc(options => { // ModelBinderProviders options.ModelBinderProviders.Insert(0, new StringBinderProvider()); // Filters options.Filters.Add(new AuthorizeFilter()); options.Filters.Add(new DataContextFilter(CsSector)); options.Filters.Add(new PrivilegeFilter()); options.Filters.Add(new FrameworkFilter()); }) .AddJsonOptions(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // custom ContractResolver options.SerializerSettings.ContractResolver = new WTMContractResolver() { //NamingStrategy = new CamelCaseNamingStrategy() }; }) .ConfigureApplicationPartManager(m => { var feature = new ControllerFeature(); if (mvc != null) { m.ApplicationParts.Add(new AssemblyPart(mvc)); } if (admin != null) { m.ApplicationParts.Add(new AssemblyPart(admin)); } m.PopulateFeature(feature); services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray()); }) .AddControllersAsServices() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; options.InvalidModelStateResponseFactory = (a) => { return(new BadRequestObjectResult(a.ModelState.GetErrorJson())); }; }) .AddDataAnnotationsLocalization(options => { var coreType = coredll?.GetTypes().Where(x => x.Name == "Program").FirstOrDefault(); options.DataAnnotationLocalizerProvider = (type, factory) => { if (Core.Program.Buildindll.Any(x => type.FullName.StartsWith(x))) { var rv = factory.Create(coreType); return(rv); } else { return(factory.Create(programType)); } }; }) .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix); services.Configure <RazorViewEngineOptions>(options => { if (mvc != null) { options.FileProviders.Add( new EmbeddedFileProvider( mvc, "WalkingTec.Mvvm.Mvc" // your external assembly's base namespace ) ); } if (admin != null) { options.FileProviders.Add( new EmbeddedFileProvider( admin, "WalkingTec.Mvvm.Mvc.Admin" // your external assembly's base namespace ) ); } }); services.Configure <FormOptions>(y => { y.ValueLengthLimit = int.MaxValue; y.MultipartBodyLengthLimit = con.FileUploadOptions.UploadLimit; }); services.AddSingleton <IUIService, DefaultUIService>(); #region CookieWithJwtAuth // services.AddSingleton<UserStore>(); services.AddSingleton <ITokenService, TokenService>(); var jwtOptions = config.GetSection("JwtOptions").Get <JwtOptions>(); if (jwtOptions == null) { jwtOptions = new JwtOptions(); } services.Configure <JwtOptions>(config.GetSection("JwtOptions")); var cookieOptions = config.GetSection("CookieOptions").Get <Core.Auth.CookieOptions>(); if (cookieOptions == null) { cookieOptions = new Core.Auth.CookieOptions(); } services.Configure <Core.Auth.CookieOptions>(config.GetSection("CookieOptions")); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.Cookie.Name = CookieAuthenticationDefaults.CookiePrefix + AuthConstants.CookieAuthName; options.Cookie.HttpOnly = true; options.Cookie.SameSite = SameSiteMode.Strict; options.ClaimsIssuer = cookieOptions.Issuer; options.SlidingExpiration = cookieOptions.SlidingExpiration; options.ExpireTimeSpan = TimeSpan.FromSeconds(cookieOptions.Expires); // options.SessionStore = new MemoryTicketStore(); options.LoginPath = cookieOptions.LoginPath; options.LogoutPath = cookieOptions.LogoutPath; options.ReturnUrlParameter = cookieOptions.ReturnUrlParameter; options.AccessDeniedPath = cookieOptions.AccessDeniedPath; }) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters = new TokenValidationParameters { NameClaimType = AuthConstants.JwtClaimTypes.Name, RoleClaimType = AuthConstants.JwtClaimTypes.Role, ValidateIssuer = true, ValidIssuer = jwtOptions.Issuer, ValidateAudience = true, ValidAudience = jwtOptions.Audience, ValidateIssuerSigningKey = false, IssuerSigningKey = jwtOptions.SymmetricSecurityKey, ValidateLifetime = true }; }); #endregion GlobalServices.SetServiceProvider(services.BuildServiceProvider()); return(services); }
public static IApplicationBuilder UseFrameworkService(this IApplicationBuilder app, Action <IRouteBuilder> customRoutes = null) { IconFontsHelper.GenerateIconFont(); var configs = app.ApplicationServices.GetRequiredService <Configs>(); var gd = app.ApplicationServices.GetRequiredService <GlobalData>(); if (configs == null) { throw new InvalidOperationException("Can not find Configs service, make sure you call AddFrameworkService at ConfigService"); } if (gd == null) { throw new InvalidOperationException("Can not find GlobalData service, make sure you call AddFrameworkService at ConfigService"); } if (string.IsNullOrEmpty(configs.Languages) == false) { List <CultureInfo> supportedCultures = new List <CultureInfo>(); var lans = configs.Languages.Split(","); foreach (var lan in lans) { supportedCultures.Add(new CultureInfo(lan)); } app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture(supportedCultures[0]), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }); } app.UseExceptionHandler(configs.ErrorHandler); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions { RequestPath = new PathString("/_js"), FileProvider = new EmbeddedFileProvider( typeof(_CodeGenController).GetTypeInfo().Assembly, "WalkingTec.Mvvm.Mvc") }); app.UseAuthentication(); app.UseResponseCaching(); bool InitDataBase = false; app.Use(async(context, next) => { if (InitDataBase == false) { var lg = app.ApplicationServices.GetRequiredService <LinkGenerator>(); foreach (var m in gd.AllModule) { //if (m.IsApi == true) //{ foreach (var a in m.Actions) { var u = lg.GetPathByAction(a.MethodName, m.ClassName, new { area = m.Area?.AreaName }); if (u == null) { u = lg.GetPathByAction(a.MethodName, m.ClassName, new { id = 0, area = m.Area?.AreaName }); } if (u != null && u.EndsWith("/0")) { u = u.Substring(0, u.Length - 2); u = u + "/{id}"; } a.Url = u; } //} } var test = app.ApplicationServices.GetService <ISpaStaticFileProvider>(); var cs = configs.ConnectionStrings; foreach (var item in cs) { var dc = item.CreateDC(); dc.DataInit(gd.AllModule, test != null).Wait(); } GlobalServices.SetServiceProvider(app.ApplicationServices); InitDataBase = true; } if (context.Request.Path == "/") { context.Response.Cookies.Append("pagemode", configs.PageMode.ToString()); context.Response.Cookies.Append("tabmode", configs.TabMode.ToString()); } try { await next.Invoke(); } catch (ConnectionResetException) { } if (context.Response.StatusCode == 404) { await context.Response.WriteAsync(string.Empty); } }); app.UseSession(); if (configs.CorsOptions.EnableAll == true) { if (configs.CorsOptions?.Policy?.Count > 0) { app.UseCors(configs.CorsOptions.Policy[0].Name); } else { app.UseCors("_donotusedefault"); } } if (customRoutes != null) { app.UseMvc(customRoutes); } else { app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } return(app); }
public static IServiceCollection AddFrameworkService(this IServiceCollection services, Func<ActionExecutingContext, string> CsSector = null, List<IDataPrivilege> dataPrivilegeSettings = null, WebHostBuilderContext webHostBuilderContext = null ) { CurrentDirectoryHelpers.SetCurrentDirectory(); IConfigurationRoot config = null; var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); if (webHostBuilderContext != null) { IHostingEnvironment env = webHostBuilderContext.HostingEnvironment; configBuilder .AddJsonFile( $"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true ); } config = configBuilder.Build(); var gd = GetGlobalData(); services.AddSingleton(gd); var con = config.Get<Configs>() ?? new Configs(); if (dataPrivilegeSettings != null) { con.DataPrivilegeSettings = dataPrivilegeSettings; } else { con.DataPrivilegeSettings = new List<IDataPrivilege>(); } services.AddSingleton(con); services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = con.CookiePre + ".Session"; options.IdleTimeout = TimeSpan.FromSeconds(3600); }); SetupDFS(con); services.AddMvc(options => { // ModelBinderProviders options.ModelBinderProviders.Insert(0, new StringBinderProvider()); // Filters options.Filters.Add(new DataContextFilter(CsSector)); options.Filters.Add(new PrivilegeFilter()); options.Filters.Add(new FrameworkFilter()); }) .AddJsonOptions(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // custom ContractResolver options.SerializerSettings.ContractResolver = new WTMContractResolver() { //NamingStrategy = new CamelCaseNamingStrategy() }; }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.Configure<RazorViewEngineOptions>(options => { options.FileProviders.Add( new EmbeddedFileProvider( typeof(_CodeGenController).GetTypeInfo().Assembly, "WalkingTec.Mvvm.Mvc" // your external assembly's base namespace ) ); var admin = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.Admin.dll").FirstOrDefault(); if (admin != null) { options.FileProviders.Add( new EmbeddedFileProvider( admin, "WalkingTec.Mvvm.Mvc.Admin" // your external assembly's base namespace ) ); } }); services.Configure<FormOptions>(y => { y.ValueLengthLimit = int.MaxValue; y.MultipartBodyLengthLimit = con.FileUploadOptions.UploadLimit; }); services.AddSingleton<IUIService, DefaultUIService>(); GlobalServices.SetServiceProvider(services.BuildServiceProvider()); return services; }
private static void UseOrleansWithSqlServer(HostBuilder hostBuilder) { hostBuilder.UseOrleans((context, builder) => { Configs con = context.Configuration.Get <Configs>() ?? new Configs(); var invariant = "System.Data.SqlClient"; var azureTableConStr = con.ConnectionStrings.FirstOrDefault(cs => cs.Key == "orleans_sql_server")?.Value; builder.UseAdoNetClustering(options => { options.Invariant = invariant; options.ConnectionString = azureTableConStr; }).ConfigureEndpoints(siloPort: 11111, gatewayPort: 30000) .Configure <ClusterOptions>(options => { options.ClusterId = "Ignite.IoT.Orleans"; options.ServiceId = "Ignite.IoT.Orleans"; }) .Configure <ProcessExitHandlingOptions>(options => options.FastKillOnProcessExit = false) .ConfigureLogging(loggingBuilder => { loggingBuilder.AddConsole(); loggingBuilder.SetMinimumLevel(LogLevel.Warning); }); builder.AddAdoNetGrainStorageAsDefault(options => { options.Invariant = invariant; options.UseJsonFormat = true; options.ConnectionString = azureTableConStr; }); builder.UseAdoNetReminderService(configure => { configure.ConnectionString = azureTableConStr; configure.Invariant = invariant; }); builder.AddSimpleMessageStreamProvider("SMSProvider") .AddMemoryGrainStorage("PubSubStore"); //builder.AddLogStorageBasedLogConsistencyProviderAsDefault(); //builder.AddStateStorageBasedLogConsistencyProviderAsDefault(); builder.ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole()); builder.ConfigureApplicationParts(parts => parts.AddFromApplicationBaseDirectory().WithReferences()); builder.UseDashboard(options => { options.Host = "*"; options.Port = 8080; options.HostSelf = true; options.CounterUpdateIntervalMs = 10000; }); var sqlServerConnStr = con.ConnectionStrings.FirstOrDefault(cs => cs.Key == "default")?.Value; builder.ConfigureServices(services => { services.AddSingleton <Configs>(con); services.AddDbContextPool <DbContext>(optionsBuilder => optionsBuilder.UseSqlServer(sqlServerConnStr) ); //services.AddDbContext<DataContext>( // optionsBuilder => // { // optionsBuilder.UseSqlServer(sqlServerConnStr); // }); GlobalServices.SetServiceProvider(services.BuildServiceProvider()); }); }); }
private static void UseOrleansWithAzureTable(HostBuilder hostBuilder) { hostBuilder.UseOrleans((context, builder) => { Configs con = context.Configuration.Get <Configs>() ?? new Configs(); var azureTableConStr = con.ConnectionStrings.FirstOrDefault(cs => cs.Key == "orleans_azure_table")?.Value; builder.UseAzureStorageClustering(options => { options.ConnectionString = azureTableConStr; options.TableName = "Cluster"; }).ConfigureEndpoints(siloPort: 11111, gatewayPort: 30000) .Configure <ClusterOptions>(options => { options.ClusterId = "Ignite.IoT.Orleans"; options.ServiceId = "Ignite.IoT.Orleans"; }) .Configure <ProcessExitHandlingOptions>(options => options.FastKillOnProcessExit = false) .ConfigureLogging(loggingBuilder => { loggingBuilder.AddConsole(); loggingBuilder.SetMinimumLevel(LogLevel.Warning); }); builder.AddAzureTableGrainStorageAsDefault(options => { options.ConnectionString = azureTableConStr; options.TableName = "Storage"; options.UseJson = true; }); builder.UseAzureTableReminderService(configure => { configure.ConnectionString = azureTableConStr; configure.TableName = "Reminder"; }); builder.ConfigureLogging(loggingBuilder => loggingBuilder.AddConsole()); builder.ConfigureApplicationParts(parts => parts.AddFromApplicationBaseDirectory().WithReferences()); builder.UseDashboard(options => { options.Host = "*"; options.Port = 8080; options.HostSelf = true; options.CounterUpdateIntervalMs = 10000; }); var sqlServerConnStr = con.ConnectionStrings.FirstOrDefault(cs => cs.Key == "default")?.Value; builder.ConfigureServices(services => { services.AddSingleton <Configs>(con); services.AddDbContextPool <DbContext>(optionsBuilder => optionsBuilder.UseSqlServer(sqlServerConnStr) ); //services.AddDbContext<DataContext>( // optionsBuilder => // { // optionsBuilder.UseSqlServer(sqlServerConnStr); // }); GlobalServices.SetServiceProvider(services.BuildServiceProvider()); }); }); }
public static IServiceCollection AddFrameworkService(this IServiceCollection services, Func <ActionExecutingContext, string> CsSector = null, List <IDataPrivilege> dataPrivilegeSettings = null, WebHostBuilderContext webHostBuilderContext = null ) { CurrentDirectoryHelpers.SetCurrentDirectory(); var configBuilder = new ConfigurationBuilder(); if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"))) { var binLocation = Assembly.GetEntryAssembly()?.Location; if (!string.IsNullOrEmpty(binLocation)) { var binPath = new FileInfo(binLocation).Directory?.FullName; if (File.Exists(Path.Combine(binPath, "appsettings.json"))) { Directory.SetCurrentDirectory(binPath); configBuilder.SetBasePath(binPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); } } } else { configBuilder.SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); } if (webHostBuilderContext != null) { var env = webHostBuilderContext.HostingEnvironment; configBuilder .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); } var config = configBuilder.Build(); var gd = GetGlobalData(); services.AddSingleton(gd); var con = config.Get <Configs>() ?? new Configs(); if (dataPrivilegeSettings != null) { con.DataPrivilegeSettings = dataPrivilegeSettings; } else { con.DataPrivilegeSettings = new List <IDataPrivilege>(); } services.AddSingleton(con); services.AddResponseCaching(); services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = con.CookiePre + ".Session"; options.IdleTimeout = TimeSpan.FromSeconds(3600); }); SetupDFS(con); services.AddCors(options => { if (con.CorsOptions?.Policy?.Count > 0) { foreach (var item in con.CorsOptions.Policy) { string[] domains = item.Domain?.Split(','); options.AddPolicy(item.Name, builder => { builder.WithOrigins(domains) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); } } else { options.AddPolicy("_donotusedefault", builder => { builder.WithOrigins("http://localhost", "https://localhost") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); } }); var mvc = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.dll").FirstOrDefault(); var admin = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.Admin.dll").FirstOrDefault(); services.AddMvc(options => { // ModelBinderProviders options.ModelBinderProviders.Insert(0, new StringBinderProvider()); // Filters options.Filters.Add(new DataContextFilter(CsSector)); options.Filters.Add(new PrivilegeFilter()); options.Filters.Add(new FrameworkFilter()); }) .AddJsonOptions(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // custom ContractResolver options.SerializerSettings.ContractResolver = new WTMContractResolver() { //NamingStrategy = new CamelCaseNamingStrategy() }; }) .ConfigureApplicationPartManager(m => { var feature = new ControllerFeature(); if (mvc != null) { m.ApplicationParts.Add(new AssemblyPart(mvc)); } if (admin != null) { m.ApplicationParts.Add(new AssemblyPart(admin)); } m.PopulateFeature(feature); services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray()); }) .AddControllersAsServices() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; options.InvalidModelStateResponseFactory = (a) => { return(new BadRequestObjectResult(a.ModelState.GetErrorJson())); }; }); services.Configure <RazorViewEngineOptions>(options => { if (mvc != null) { options.FileProviders.Add( new EmbeddedFileProvider( mvc, "WalkingTec.Mvvm.Mvc" // your external assembly's base namespace ) ); } if (admin != null) { options.FileProviders.Add( new EmbeddedFileProvider( admin, "WalkingTec.Mvvm.Mvc.Admin" // your external assembly's base namespace ) ); } }); services.Configure <FormOptions>(y => { y.ValueLengthLimit = int.MaxValue; y.MultipartBodyLengthLimit = con.FileUploadOptions.UploadLimit; }); services.AddSingleton <IUIService, DefaultUIService>(); GlobalServices.SetServiceProvider(services.BuildServiceProvider()); return(services); }
public static IServiceCollection AddFrameworkService(this IServiceCollection services, Func <ActionExecutingContext, string> CsSector = null, List <IDataPrivilege> dataPrivilegeSettings = null, WebHostBuilderContext webHostBuilderContext = null ) { CurrentDirectoryHelpers.SetCurrentDirectory(); IConfigurationRoot config = null; var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); if (webHostBuilderContext != null) { IHostingEnvironment env = webHostBuilderContext.HostingEnvironment; configBuilder .AddJsonFile( $"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true ); } config = configBuilder.Build(); var gd = GetGlobalData(); services.AddSingleton(gd); var con = config.Get <Configs>() ?? new Configs(); AppSeetingConfig.AppSettings = con.AppSettings; if (dataPrivilegeSettings != null) { con.DataPrivilegeSettings = dataPrivilegeSettings; } else { con.DataPrivilegeSettings = new List <IDataPrivilege>(); } services.AddSingleton(con); services.AddResponseCaching(); services.AddMemoryCache(); services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = con.CookiePre + ".Session"; options.IdleTimeout = TimeSpan.FromSeconds(3600); }); SetupDFS(con); var mvc = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.dll").FirstOrDefault(); var admin = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.Admin.dll").FirstOrDefault(); services.AddMvc(options => { // ModelBinderProviders options.ModelBinderProviders.Insert(0, new StringBinderProvider()); // Filters options.Filters.Add(new DataContextFilter(CsSector)); options.Filters.Add(new PrivilegeFilter()); options.Filters.Add(new FrameworkFilter()); }) .AddJsonOptions(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // custom ContractResolver options.SerializerSettings.ContractResolver = new WTMContractResolver() { //NamingStrategy = new CamelCaseNamingStrategy() }; }) .ConfigureApplicationPartManager(m => { var feature = new ControllerFeature(); if (mvc != null) { m.ApplicationParts.Add(new AssemblyPart(mvc)); } if (admin != null) { m.ApplicationParts.Add(new AssemblyPart(admin)); } m.PopulateFeature(feature); services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray()); }) .AddControllersAsServices() .SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .ConfigureApiBehaviorOptions(options => { options.SuppressModelStateInvalidFilter = true; options.InvalidModelStateResponseFactory = (a) => { return(new BadRequestObjectResult(a.ModelState.GetErrorJson())); }; }); services.Configure <RazorViewEngineOptions>(options => { if (mvc != null) { options.FileProviders.Add( new EmbeddedFileProvider( mvc, "WalkingTec.Mvvm.Mvc" // your external assembly's base namespace ) ); } if (admin != null) { options.FileProviders.Add( new EmbeddedFileProvider( admin, "WalkingTec.Mvvm.Mvc.Admin" // your external assembly's base namespace ) ); } }); services.Configure <FormOptions>(y => { y.ValueLengthLimit = int.MaxValue; y.MultipartBodyLengthLimit = con.FileUploadOptions.UploadLimit; y.MemoryBufferThreshold = con.FileUploadOptions.UploadLimit; }); services.AddSingleton <IUIService, DefaultUIService>(); GlobalServices.SetServiceProvider(services.BuildServiceProvider()); return(services); }