From d198d46cbcff4eca6ec8f824b1c6d14a4cf8e1b3 Mon Sep 17 00:00:00 2001 From: xuejiaming <326308290@qq.com> Date: Fri, 1 Jul 2022 23:29:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E6=A0=B7=E4=BE=8B=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/CommonController.cs | 146 ++++++------- .../Controllers/TestController.cs | 74 +++---- .../Middlewares/TenantSelectMiddleware.cs | 94 ++++---- samples/Sample.MultiConfig/Program.cs | 104 +++++---- .../Controllers/WeatherForecastController.cs | 2 - samples/Sample.MySql/DIExtension.cs | 7 - samples/Sample.MySql/Startup.cs | 29 +-- .../Controllers/ValuesController.cs | 32 +-- samples/Sample.SqlServer/DIExtension.cs | 7 - samples/Sample.SqlServer/DbContextHelper.cs | 5 +- samples/Sample.SqlServer/Startup.cs | 29 +-- .../ShardingCoreSqlServerExtension.cs | 2 +- .../EntityMetadataEnsureParams.cs | 28 --- .../EntityMetadataInitializer.cs | 17 +- .../Bootstrappers/IShardingBootstrapper.cs | 8 +- .../Bootstrappers/ShardingBootstrapper.cs | 61 +++++- .../ShardingDbContextBootstrapper.cs | 115 ---------- src/ShardingCore/Core/IShardingProvider.cs | 4 + .../IShardingRouteConfigOptions.cs | 90 +++++--- .../ShardingCoreConfigBuilder.cs | 205 +++++++----------- .../ShardingConfigOptions.cs | 20 ++ .../ShardingRouteConfigOptions.cs | 21 ++ src/ShardingCore/Core/ShardingProvider.cs | 19 ++ .../Core/ShardingRuntimeContext.cs | 2 +- .../ShardingCoreConfigBuilderExtension.cs | 21 -- .../Extensions/ShardingProviderExtension.cs | 19 -- src/ShardingCore/Jobs/Abstaractions/IJob.cs | 1 - .../Jobs/Abstaractions/IJobManager.cs | 2 +- src/ShardingCore/Jobs/JobRunnerService.cs | 4 +- src/ShardingCore/ShardingCoreExtension.cs | 59 ++--- src/ShardingCore/ShardingRuntimeBuilder.cs | 67 +++--- .../TableCreator/ShardingTableCreator.cs | 5 +- 32 files changed, 550 insertions(+), 749 deletions(-) delete mode 100644 src/ShardingCore/Bootstrappers/EntityMetadataEnsureParams.cs delete mode 100644 src/ShardingCore/Bootstrappers/ShardingDbContextBootstrapper.cs delete mode 100644 src/ShardingCore/Extensions/ShardingCoreConfigBuilderExtension.cs diff --git a/samples/Sample.MultiConfig/Controllers/CommonController.cs b/samples/Sample.MultiConfig/Controllers/CommonController.cs index 1f485e91..6fae6dd6 100644 --- a/samples/Sample.MultiConfig/Controllers/CommonController.cs +++ b/samples/Sample.MultiConfig/Controllers/CommonController.cs @@ -1,73 +1,73 @@ -using System.Data.Common; -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using ShardingCore.Core; -using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions; -using ShardingCore.DynamicDataSources; -using ShardingCore.Sharding.ReadWriteConfigurations; -using ShardingCore.Sharding.ShardingComparision.Abstractions; -using ShardingCore.TableExists.Abstractions; - -namespace Sample.MultiConfig.Controllers -{ - [ApiController] - [Route("[controller]/[action]")] - public class CommonController : ControllerBase - { - private readonly IVirtualDataSourceManager _virtualDataSourceManager; - - public CommonController(IVirtualDataSourceManager virtualDataSourceManager) - { - _virtualDataSourceManager = virtualDataSourceManager; - } - public async Task DynamicAdd(string configId) - { - var flag = DynamicDataSourceHelper.DynamicAppendVirtualDataSource(new MySqlConfigurationParam(configId)); - return Ok(flag?"成功":"失败"); - } - } - - public class MySqlConfigurationParam : AbstractVirtualDataSourceConfigurationParams - { - public override string ConfigId { get; } - public override int Priority { get; } - public override string DefaultDataSourceName { get; } - public override string DefaultConnectionString { get; } - public override IDictionary ReadWriteNodeSeparationConfigs { get; } - public override ReadStrategyEnum? ReadStrategy { get; } - public override bool? ReadWriteDefaultEnable { get; } - public override int? ReadWriteDefaultPriority { get; } - public override ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; } - - public MySqlConfigurationParam(string configId) - { - ConfigId = configId; - DefaultDataSourceName = "ds0"; - DefaultConnectionString = $"server=127.0.0.1;port=3306;database=MultiConfigSharding{configId};userid=root;password=L6yBtV6qNENrwBy7;"; - } - - public override DbContextOptionsBuilder UseDbContextOptionsBuilder(string connectionString, - DbContextOptionsBuilder dbContextOptionsBuilder) - { - dbContextOptionsBuilder.UseMySql(connectionString,new MySqlServerVersion(new Version())); - return dbContextOptionsBuilder; - } - - public override DbContextOptionsBuilder UseDbContextOptionsBuilder(DbConnection dbConnection, - DbContextOptionsBuilder dbContextOptionsBuilder) - { - dbContextOptionsBuilder.UseMySql(dbConnection, new MySqlServerVersion(new Version())); - return dbContextOptionsBuilder; - } - - public override void UseShellDbContextOptionBuilder(DbContextOptionsBuilder dbContextOptionsBuilder) - { - - } - - public override void UseExecutorDbContextOptionBuilder(DbContextOptionsBuilder dbContextOptionsBuilder) - { - - } - } -} +// using System.Data.Common; +// using Microsoft.AspNetCore.Mvc; +// using Microsoft.EntityFrameworkCore; +// using ShardingCore.Core; +// using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions; +// using ShardingCore.DynamicDataSources; +// using ShardingCore.Sharding.ReadWriteConfigurations; +// using ShardingCore.Sharding.ShardingComparision.Abstractions; +// using ShardingCore.TableExists.Abstractions; +// +// namespace Sample.MultiConfig.Controllers +// { +// [ApiController] +// [Route("[controller]/[action]")] +// public class CommonController : ControllerBase +// { +// private readonly IVirtualDataSourceManager _virtualDataSourceManager; +// +// public CommonController(IVirtualDataSourceManager virtualDataSourceManager) +// { +// _virtualDataSourceManager = virtualDataSourceManager; +// } +// public async Task DynamicAdd(string configId) +// { +// var flag = DynamicDataSourceHelper.DynamicAppendVirtualDataSource(new MySqlConfigurationParam(configId)); +// return Ok(flag?"成功":"失败"); +// } +// } +// +// public class MySqlConfigurationParam : AbstractVirtualDataSourceConfigurationParams +// { +// public override string ConfigId { get; } +// public override int Priority { get; } +// public override string DefaultDataSourceName { get; } +// public override string DefaultConnectionString { get; } +// public override IDictionary ReadWriteNodeSeparationConfigs { get; } +// public override ReadStrategyEnum? ReadStrategy { get; } +// public override bool? ReadWriteDefaultEnable { get; } +// public override int? ReadWriteDefaultPriority { get; } +// public override ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; } +// +// public MySqlConfigurationParam(string configId) +// { +// ConfigId = configId; +// DefaultDataSourceName = "ds0"; +// DefaultConnectionString = $"server=127.0.0.1;port=3306;database=MultiConfigSharding{configId};userid=root;password=L6yBtV6qNENrwBy7;"; +// } +// +// public override DbContextOptionsBuilder UseDbContextOptionsBuilder(string connectionString, +// DbContextOptionsBuilder dbContextOptionsBuilder) +// { +// dbContextOptionsBuilder.UseMySql(connectionString,new MySqlServerVersion(new Version())); +// return dbContextOptionsBuilder; +// } +// +// public override DbContextOptionsBuilder UseDbContextOptionsBuilder(DbConnection dbConnection, +// DbContextOptionsBuilder dbContextOptionsBuilder) +// { +// dbContextOptionsBuilder.UseMySql(dbConnection, new MySqlServerVersion(new Version())); +// return dbContextOptionsBuilder; +// } +// +// public override void UseShellDbContextOptionBuilder(DbContextOptionsBuilder dbContextOptionsBuilder) +// { +// +// } +// +// public override void UseExecutorDbContextOptionBuilder(DbContextOptionsBuilder dbContextOptionsBuilder) +// { +// +// } +// } +// } diff --git a/samples/Sample.MultiConfig/Controllers/TestController.cs b/samples/Sample.MultiConfig/Controllers/TestController.cs index ebe6b4d3..d4ba5e00 100644 --- a/samples/Sample.MultiConfig/Controllers/TestController.cs +++ b/samples/Sample.MultiConfig/Controllers/TestController.cs @@ -1,37 +1,37 @@ -using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Sample.MultiConfig.Domain.Entities; -using ShardingCore.Core.VirtualDatabase.VirtualTables; - -namespace Sample.MultiConfig.Controllers -{ - [ApiController] - [Route("[controller]/[action]")] - public class TestController:ControllerBase - { - private readonly MultiConfigDbContext _multiConfigDbContext; - private readonly IVirtualTableManager _virtualTableManager; - - public TestController(MultiConfigDbContext multiConfigDbContext,IVirtualTableManager virtualTableManager) - { - _multiConfigDbContext = multiConfigDbContext; - _virtualTableManager = virtualTableManager; - } - public async Task Add() - { - var order = new Order(); - order.Id = Guid.NewGuid().ToString("n"); - order.Name = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); - order.CreateTime=DateTime.Now; - await _multiConfigDbContext.AddAsync(order); - await _multiConfigDbContext.SaveChangesAsync(); - return Ok(); - } - public async Task Query() - { - var listAsync = await _multiConfigDbContext.Set().ToListAsync(); - return Ok(listAsync); - } - - } -} +// using Microsoft.AspNetCore.Mvc; +// using Microsoft.EntityFrameworkCore; +// using Sample.MultiConfig.Domain.Entities; +// using ShardingCore.Core.VirtualDatabase.VirtualTables; +// +// namespace Sample.MultiConfig.Controllers +// { +// [ApiController] +// [Route("[controller]/[action]")] +// public class TestController:ControllerBase +// { +// private readonly MultiConfigDbContext _multiConfigDbContext; +// private readonly IVirtualTableManager _virtualTableManager; +// +// public TestController(MultiConfigDbContext multiConfigDbContext,IVirtualTableManager virtualTableManager) +// { +// _multiConfigDbContext = multiConfigDbContext; +// _virtualTableManager = virtualTableManager; +// } +// public async Task Add() +// { +// var order = new Order(); +// order.Id = Guid.NewGuid().ToString("n"); +// order.Name = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); +// order.CreateTime=DateTime.Now; +// await _multiConfigDbContext.AddAsync(order); +// await _multiConfigDbContext.SaveChangesAsync(); +// return Ok(); +// } +// public async Task Query() +// { +// var listAsync = await _multiConfigDbContext.Set().ToListAsync(); +// return Ok(listAsync); +// } +// +// } +// } diff --git a/samples/Sample.MultiConfig/Middlewares/TenantSelectMiddleware.cs b/samples/Sample.MultiConfig/Middlewares/TenantSelectMiddleware.cs index 041ce37f..d4d89e76 100644 --- a/samples/Sample.MultiConfig/Middlewares/TenantSelectMiddleware.cs +++ b/samples/Sample.MultiConfig/Middlewares/TenantSelectMiddleware.cs @@ -1,47 +1,47 @@ -using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions; - -namespace Sample.MultiConfig.Middlewares -{ - public class TenantSelectMiddleware - { - private readonly RequestDelegate _next; - private readonly IVirtualDataSourceManager _virtualDataSourceManager; - - public TenantSelectMiddleware(RequestDelegate next, IVirtualDataSourceManager virtualDataSourceManager) - { - _next = next; - _virtualDataSourceManager = virtualDataSourceManager; - } - - /// - /// 1.中间件的方法必须叫Invoke,且为public,非static。 - /// 2.Invoke方法第一个参数必须是HttpContext类型。 - /// 3.Invoke方法必须返回Task。 - /// 4.Invoke方法可以有多个参数,除HttpContext外其它参数会尝试从依赖注入容器中获取。 - /// 5.Invoke方法不能有重载。 - /// - /// Author : Napoleon - /// Created : 2020/1/30 21:30 - public async Task Invoke(HttpContext context) - { - if (context.Request.Path.ToString().StartsWith("/test", StringComparison.CurrentCultureIgnoreCase)) - { - if (!context.Request.Headers.ContainsKey("TenantId") || !_virtualDataSourceManager.ContansConfigId(context.Request.Headers["TenantId"])) - { - context.Response.StatusCode = 403; //UnAuthorized - await context.Response.WriteAsync("403 not found TenantId"); - return; - } - - using (_virtualDataSourceManager.CreateScope(context.Request.Headers["TenantId"])) - { - await _next(context); - } - } - else - { - await _next(context); - } - } - } -} +// using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions; +// +// namespace Sample.MultiConfig.Middlewares +// { +// public class TenantSelectMiddleware +// { +// private readonly RequestDelegate _next; +// private readonly IVirtualDataSourceManager _virtualDataSourceManager; +// +// public TenantSelectMiddleware(RequestDelegate next, IVirtualDataSourceManager virtualDataSourceManager) +// { +// _next = next; +// _virtualDataSourceManager = virtualDataSourceManager; +// } +// +// /// +// /// 1.中间件的方法必须叫Invoke,且为public,非static。 +// /// 2.Invoke方法第一个参数必须是HttpContext类型。 +// /// 3.Invoke方法必须返回Task。 +// /// 4.Invoke方法可以有多个参数,除HttpContext外其它参数会尝试从依赖注入容器中获取。 +// /// 5.Invoke方法不能有重载。 +// /// +// /// Author : Napoleon +// /// Created : 2020/1/30 21:30 +// public async Task Invoke(HttpContext context) +// { +// if (context.Request.Path.ToString().StartsWith("/test", StringComparison.CurrentCultureIgnoreCase)) +// { +// if (!context.Request.Headers.ContainsKey("TenantId") || !_virtualDataSourceManager.ContansConfigId(context.Request.Headers["TenantId"])) +// { +// context.Response.StatusCode = 403; //UnAuthorized +// await context.Response.WriteAsync("403 not found TenantId"); +// return; +// } +// +// using (_virtualDataSourceManager.CreateScope(context.Request.Headers["TenantId"])) +// { +// await _next(context); +// } +// } +// else +// { +// await _next(context); +// } +// } +// } +// } diff --git a/samples/Sample.MultiConfig/Program.cs b/samples/Sample.MultiConfig/Program.cs index e198f8ab..ba9e6cf1 100644 --- a/samples/Sample.MultiConfig/Program.cs +++ b/samples/Sample.MultiConfig/Program.cs @@ -1,64 +1,60 @@ using Microsoft.EntityFrameworkCore; using Sample.MultiConfig; -using Sample.MultiConfig.Middlewares; using ShardingCore; using ShardingCore.Bootstrappers; -using ShardingCore.TableExists; var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. - - ILoggerFactory efLogger = LoggerFactory.Create(builder => -{ - builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole(); -}); -builder.Services.AddControllers(); -builder.Services.AddShardingDbContext() - .AddEntityConfig(op => - { - op.CreateShardingTableOnStart = true; - op.EnsureCreatedWithOutShardingTable = true; - op.AddShardingTableRoute(); - }) - .AddConfig(op => - { - op.ConfigId = "c1"; - op.UseShardingQuery((conStr, b) => - { - b.UseSqlServer(conStr).UseLoggerFactory(efLogger); - }); - op.UseShardingTransaction((conn, b) => - { - b.UseSqlServer(conn).UseLoggerFactory(efLogger); - }); - op.AddDefaultDataSource("ds0", - "Data Source=localhost;Initial Catalog=MultiConfigSharding;Integrated Security=True;"); - op.ReplaceTableEnsureManager(sp => new SqlServerTableEnsureManager()); - }) - .AddConfig(op => - { - op.ConfigId = "c2"; - op.UseShardingQuery((conStr, b) => - { - b.UseMySql(conStr, new MySqlServerVersion(new Version())).UseLoggerFactory(efLogger); - }); - op.UseShardingTransaction((conn, b) => - { - b.UseMySql(conn, new MySqlServerVersion(new Version())).UseLoggerFactory(efLogger); - }); - op.AddDefaultDataSource("ds0", - "server=127.0.0.1;port=3306;database=MultiConfigSharding;userid=root;password=L6yBtV6qNENrwBy7;"); - op.ReplaceTableEnsureManager(sp => new MySqlTableEnsureManager()); - }).EnsureMultiConfig(); - +// +// // Add services to the container. +// +// ILoggerFactory efLogger = LoggerFactory.Create(builder => +// { +// builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole(); +// }); +// builder.Services.AddControllers(); +// builder.Services.AddShardingDbContext() +// .AddEntityConfig(op => +// { +// op.AddShardingTableRoute(); +// }) +// .AddConfig(op => +// { +// // op.ConfigId = "c1"; +// op.UseShardingQuery((conStr, b) => +// { +// b.UseSqlServer(conStr).UseLoggerFactory(efLogger); +// }); +// op.UseShardingTransaction((conn, b) => +// { +// b.UseSqlServer(conn).UseLoggerFactory(efLogger); +// }); +// op.AddDefaultDataSource("ds0", +// "Data Source=localhost;Initial Catalog=MultiConfigSharding;Integrated Security=True;"); +// // op.ReplaceTableEnsureManager(sp => new SqlServerTableEnsureManager()); +// }) +// .AddConfig(op => +// { +// op.ConfigId = "c2"; +// op.UseShardingQuery((conStr, b) => +// { +// b.UseMySql(conStr, new MySqlServerVersion(new Version())).UseLoggerFactory(efLogger); +// }); +// op.UseShardingTransaction((conn, b) => +// { +// b.UseMySql(conn, new MySqlServerVersion(new Version())).UseLoggerFactory(efLogger); +// }); +// op.AddDefaultDataSource("ds0", +// "server=127.0.0.1;port=3306;database=MultiConfigSharding;userid=root;password=L6yBtV6qNENrwBy7;"); +// op.ReplaceTableEnsureManager(sp => new MySqlTableEnsureManager()); +// }).EnsureMultiConfig(); +// var app = builder.Build(); - -// Configure the HTTP request pipeline. -app.Services.GetRequiredService().Start(); +// +// // Configure the HTTP request pipeline. +// app.Services.GetRequiredService().Start(); app.UseAuthorization(); -app.UseMiddleware(); - +// app.UseMiddleware(); +// app.MapControllers(); - +// app.Run(); diff --git a/samples/Sample.MySql/Controllers/WeatherForecastController.cs b/samples/Sample.MySql/Controllers/WeatherForecastController.cs index 07272913..2a0449f1 100644 --- a/samples/Sample.MySql/Controllers/WeatherForecastController.cs +++ b/samples/Sample.MySql/Controllers/WeatherForecastController.cs @@ -26,8 +26,6 @@ namespace Sample.MySql.Controllers [HttpGet] public async Task Get() { - - var result = await _defaultTableDbContext.Set().AnyAsync(); var result1 = await _defaultTableDbContext.Set().Where(o => o.Id == "2" || o.Id == "3").ToListAsync(); var result2 = await _defaultTableDbContext.Set().Skip(1).Take(10).ToListAsync(); diff --git a/samples/Sample.MySql/DIExtension.cs b/samples/Sample.MySql/DIExtension.cs index b00bd08f..56ead53f 100644 --- a/samples/Sample.MySql/DIExtension.cs +++ b/samples/Sample.MySql/DIExtension.cs @@ -17,13 +17,6 @@ namespace Sample.MySql */ public static class DIExtension { - public static IApplicationBuilder UseShardingCore(this IApplicationBuilder app) - { - var shardingBootstrapper = app.ApplicationServices.GetRequiredService(); - shardingBootstrapper.Start(); - return app; - } - public static void DbSeed(this IApplicationBuilder app) { using (var scope=app.ApplicationServices.CreateScope()) diff --git a/samples/Sample.MySql/Startup.cs b/samples/Sample.MySql/Startup.cs index dda07471..87038261 100644 --- a/samples/Sample.MySql/Startup.cs +++ b/samples/Sample.MySql/Startup.cs @@ -47,21 +47,13 @@ namespace Sample.MySql { o.UseShardingQuery((conStr,builder)=> { - builder.UseMySql(conStr, new MySqlServerVersion(new Version()) - // ,b=>b.EnableRetryOnFailure() - ) - .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); + builder.UseMySql(conStr, new MySqlServerVersion(new Version())).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); }); o.UseShardingTransaction((connection, builder) => { - builder.UseMySql(connection, new MySqlServerVersion(new Version()) - // ,b=>b.EnableRetryOnFailure() - ) - .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); + builder.UseMySql(connection, new MySqlServerVersion(new Version())).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); }); - o.AddDefaultDataSource("ds0", - "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); - + o.AddDefaultDataSource("ds0","server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); }) .Build(sp); }); @@ -111,21 +103,6 @@ namespace Sample.MySql { app.UseDeveloperExceptionPage(); } - - // app.UseShardingCore(); - // - // - // using (var serviceScope = app.ApplicationServices.CreateScope()) - // { - // var defaultShardingDbContext = serviceScope.ServiceProvider.GetService(); - // } - // - // Console.WriteLine("------------------"); - // using (var serviceScope = app.ApplicationServices.CreateScope()) - // { - // var defaultShardingDbContext = serviceScope.ServiceProvider.GetService(); - // } - // Console.WriteLine("------------------"); app.UseRouting(); app.UseAuthorization(); diff --git a/samples/Sample.SqlServer/Controllers/ValuesController.cs b/samples/Sample.SqlServer/Controllers/ValuesController.cs index c04e8a2f..cf94c02e 100644 --- a/samples/Sample.SqlServer/Controllers/ValuesController.cs +++ b/samples/Sample.SqlServer/Controllers/ValuesController.cs @@ -5,21 +5,15 @@ using Sample.SqlServer.DbContexts; using Sample.SqlServer.Domain.Entities; using ShardingCore.Core.QueryRouteManagers.Abstractions; using ShardingCore.Extensions; -using ShardingCore.Extensions.ShardingPageExtensions; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; -using ShardingCore; -using ShardingCore.Core.VirtualDatabase.VirtualTables; using ShardingCore.Core.VirtualRoutes.TableRoutes; -using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine; using ShardingCore.Extensions.ShardingQueryableExtensions; -using ShardingCore.Sharding.Abstractions; -using Microsoft.EntityFrameworkCore.Query.Internal; -using ShardingCore.EFCores; +using ShardingCore.Core; using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions; namespace Sample.SqlServer.Controllers @@ -36,39 +30,23 @@ namespace Sample.SqlServer.Controllers private readonly DefaultShardingDbContext _defaultTableDbContext; private readonly IShardingRouteManager _shardingRouteManager; private readonly IShardingReadWriteManager _readWriteManager; + private readonly IShardingRuntimeContext _shardingRuntimeContext; - public ValuesController(DefaultShardingDbContext defaultTableDbContext, IShardingRouteManager shardingRouteManager,IShardingReadWriteManager readWriteManager) + public ValuesController(DefaultShardingDbContext defaultTableDbContext, IShardingRouteManager shardingRouteManager,IShardingReadWriteManager readWriteManager,IShardingRuntimeContext shardingRuntimeContext) { _defaultTableDbContext = defaultTableDbContext; _ = defaultTableDbContext.Model; _shardingRouteManager = shardingRouteManager; _readWriteManager = readWriteManager; + _shardingRuntimeContext = shardingRuntimeContext; } [HttpGet] public async Task Get2x() { - _defaultTableDbContext.ChangeTracker.HasChanges(); - //var queryable = _defaultTableDbContext.Set().Where(o=>true); - - //var tableRouteRuleEngineFactory = ShardingContainer.GetService>(); - //var tableRouteResults = tableRouteRuleEngineFactory.Route(queryable); - var virtualTableManager = ShardingContainer.GetService>(); - var virtualTable = virtualTableManager.GetVirtualTable(); - - var physicTable1s = virtualTable.RouteTo(new ShardingTableRouteConfig(shardingKeyValue: "123"));//获取值为123的所有分片 - - Expression> where = o => o.Id == "123"; - var physicTable2s = virtualTable.RouteTo(new ShardingTableRouteConfig(predicate: where));//获取表达式o.Id == "123"的所有路由 - - var allPhysicTables = virtualTable.GetAllPhysicTables(); - - var virtualTableRoute = virtualTable.GetVirtualRoute(); - var allTails = virtualTableRoute.GetAllTails(); - Console.WriteLine("------------------Get2x------------------------"); using (var dbContext = DbContextHelper.CreateDbContextByString( - "Data Source=localhost;Initial Catalog=ShardingCoreDBXA;Integrated Security=True;")) + "Data Source=localhost;Initial Catalog=ShardingCoreDBXA;Integrated Security=True;",_shardingRuntimeContext)) { await dbContext.AddAsync(new SysUserMod() { diff --git a/samples/Sample.SqlServer/DIExtension.cs b/samples/Sample.SqlServer/DIExtension.cs index 5b0edf92..eda0c3dd 100644 --- a/samples/Sample.SqlServer/DIExtension.cs +++ b/samples/Sample.SqlServer/DIExtension.cs @@ -19,13 +19,6 @@ namespace Sample.SqlServer */ public static class DIExtension { - public static IApplicationBuilder UseShardingCore(this IApplicationBuilder app) - { - var shardingBootstrapper = app.ApplicationServices.GetRequiredService(); - shardingBootstrapper.Start(); - return app; - } - public static void DbSeed(this IApplicationBuilder app) { using (var scope = app.ApplicationServices.CreateScope()) diff --git a/samples/Sample.SqlServer/DbContextHelper.cs b/samples/Sample.SqlServer/DbContextHelper.cs index 37ddb3e0..24d00812 100644 --- a/samples/Sample.SqlServer/DbContextHelper.cs +++ b/samples/Sample.SqlServer/DbContextHelper.cs @@ -1,15 +1,16 @@ using Microsoft.EntityFrameworkCore; using Sample.SqlServer.DbContexts; using ShardingCore; +using ShardingCore.Core; namespace Sample.SqlServer { public class DbContextHelper { - public static DbContext CreateDbContextByString(string connectionString) + public static DbContext CreateDbContextByString(string connectionString,IShardingRuntimeContext shardingRuntimeContext) { var dbContextOptionsBuilder = new DbContextOptionsBuilder(); - dbContextOptionsBuilder.UseSqlServer(connectionString).UseSharding(); + dbContextOptionsBuilder.UseSqlServer(connectionString).UseSharding(shardingRuntimeContext); return new DefaultShardingDbContext(dbContextOptionsBuilder.Options); } } diff --git a/samples/Sample.SqlServer/Startup.cs b/samples/Sample.SqlServer/Startup.cs index cd46ff02..f00a802f 100644 --- a/samples/Sample.SqlServer/Startup.cs +++ b/samples/Sample.SqlServer/Startup.cs @@ -1,6 +1,5 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; -using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; @@ -8,17 +7,10 @@ using Sample.SqlServer.DbContexts; using Sample.SqlServer.Shardings; using Sample.SqlServer.UnionAllMerge; using ShardingCore; -using ShardingCore.TableExists; using System; using System.Collections.Generic; using System.Diagnostics; -using Microsoft.Extensions.DependencyInjection.Extensions; -using ShardingCore.Core.DbContextCreator; -using ShardingCore.EFCores.OptionsExtensions; -using ShardingCore.Helpers; using ShardingCore.Sharding.ReadWriteConfigurations; -using ShardingCore.Sharding.ShardingComparision; -using ShardingCore.Sharding.ShardingComparision.Abstractions; namespace Sample.SqlServer { @@ -41,25 +33,21 @@ namespace Sample.SqlServer //services.AddDbContext(o => o.UseSqlServer("Data Source=localhost;Initial Catalog=ShardingCoreDBxx3;Integrated Security=True")); services.AddShardingDbContext() - .AddEntityConfig(o => + .UseRouteConfig(o => { o.ThrowIfQueryRouteNotMatch = false; - o.CreateShardingTableOnStart = true; - o.EnsureCreatedWithOutShardingTable = true; o.AddShardingTableRoute(); o.AddShardingTableRoute(); o.AddShardingTableRoute(); }) - .AddConfig(op => + .UseConfig((sp,op) => { - op.ConfigId = "c1"; op.MaxQueryConnectionsLimit = 5; op.UseSqlServer(builder => { - var loggerFactory = ShardingContainer.GetService(); + var loggerFactory = sp.GetService(); builder.UseLoggerFactory(loggerFactory).UseUnionAllMerge(); }); - op.ReplaceTableEnsureManager(sp => new SqlServerTableEnsureManager()); op.AddDefaultDataSource("A", "Data Source=localhost;Initial Catalog=ShardingCoreDBXA;Integrated Security=True;" ); @@ -81,7 +69,7 @@ namespace Sample.SqlServer new ReadNode("X","Data Source=localhost;Initial Catalog=ShardingCoreDBXA123;Integrated Security=True;"), }} },ReadStrategyEnum.Loop); - }).EnsureConfig(); + }).AddShardingCore(); //services.AddShardingDbContext( // (conn, o) => // o.UseSqlServer(conn).UseLoggerFactory(efLogger) @@ -137,17 +125,10 @@ namespace Sample.SqlServer } - var startNew = Stopwatch.StartNew(); - startNew.Start(); - app.UseShardingCore(); - startNew.Stop(); - Console.WriteLine($"UseShardingCore:" + startNew.ElapsedMilliseconds + "ms"); - - app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); - DynamicShardingHelper.DynamicAppendDataSource("c1","B", "Data Source=localhost;Initial Catalog=ShardingCoreDBXAABB;Integrated Security=True;"); + // DynamicShardingHelper.DynamicAppendDataSource("c1","B", "Data Source=localhost;Initial Catalog=ShardingCoreDBXAABB;Integrated Security=True;"); app.DbSeed(); } } diff --git a/samples/Sample.SqlServer/UnionAllMerge/ShardingCoreSqlServerExtension.cs b/samples/Sample.SqlServer/UnionAllMerge/ShardingCoreSqlServerExtension.cs index ddfd9dc7..cd5c9da0 100644 --- a/samples/Sample.SqlServer/UnionAllMerge/ShardingCoreSqlServerExtension.cs +++ b/samples/Sample.SqlServer/UnionAllMerge/ShardingCoreSqlServerExtension.cs @@ -11,7 +11,7 @@ namespace Sample.SqlServer.UnionAllMerge { public static class ShardingCoreSqlServerExtension { - public static void UseSqlServer(this ShardingConfigOptions option,Action builderConfigure=null) where TShardingDbContext : DbContext, IShardingDbContext + public static void UseSqlServer(this ShardingConfigOptions option,Action builderConfigure=null) { option.UseShardingQuery((conStr, builder) => { diff --git a/src/ShardingCore/Bootstrappers/EntityMetadataEnsureParams.cs b/src/ShardingCore/Bootstrappers/EntityMetadataEnsureParams.cs deleted file mode 100644 index 315f9023..00000000 --- a/src/ShardingCore/Bootstrappers/EntityMetadataEnsureParams.cs +++ /dev/null @@ -1,28 +0,0 @@ -// using Microsoft.EntityFrameworkCore.Metadata; -// using ShardingCore.Core.EntityMetadatas; -// using ShardingCore.Extensions.InternalExtensions; -// -// /* -// * @Author: xjm -// * @Description: -// * @Ver: 1.0 -// * @Email: 326308290@qq.com -// */ -// namespace ShardingCore.Bootstrappers -// { -// /// -// /// 分表、分库对象确定参数用来初始化时所需的信息 -// /// -// public class EntityMetadataEnsureParams -// { -// public EntityMetadataEnsureParams(IEntityType entityType) -// { -// EntityType = entityType; -// -// VirtualTableName = entityType.GetEntityTypeTableName(); -// } -// -// public IEntityType EntityType { get; } -// public string VirtualTableName { get; } -// } -// } diff --git a/src/ShardingCore/Bootstrappers/EntityMetadataInitializer.cs b/src/ShardingCore/Bootstrappers/EntityMetadataInitializer.cs index 6ea54e67..40200f12 100644 --- a/src/ShardingCore/Bootstrappers/EntityMetadataInitializer.cs +++ b/src/ShardingCore/Bootstrappers/EntityMetadataInitializer.cs @@ -27,42 +27,31 @@ namespace ShardingCore.Bootstrappers /// /// 对象元数据初始化器 /// - /// /// public class EntityMetadataInitializer: IEntityMetadataInitializer where TEntity:class { private static readonly ILogger> _logger=InternalLoggerFactory.CreateLogger>(); - // private const string QueryFilter = "QueryFilter"; - // private readonly IEntityType _entityType; - // private readonly string _virtualTableName; - // private readonly Expression> _queryFilterExpression; private readonly Type _shardingEntityType; private readonly IShardingProvider _shardingProvider; private readonly IShardingRouteConfigOptions _shardingRouteConfigOptions; private readonly IVirtualDataSourceRouteManager _virtualDataSourceRouteManager; private readonly ITableRouteManager _tableRouteManager; private readonly IEntityMetadataManager _entityMetadataManager; - private readonly IJobManager _jobManager; public EntityMetadataInitializer( IShardingProvider shardingProvider, IShardingRouteConfigOptions shardingRouteConfigOptions, IVirtualDataSourceRouteManager virtualDataSourceRouteManager, ITableRouteManager tableRouteManager, - IEntityMetadataManager entityMetadataManager, - IJobManager jobManager + IEntityMetadataManager entityMetadataManager ) { _shardingEntityType = typeof(TEntity); - // _entityType = entityMetadataEnsureParams.EntityType; - // _virtualTableName = entityMetadataEnsureParams.VirtualTableName; - // _queryFilterExpression = entityMetadataEnsureParams.EntityType.GetAnnotations().FirstOrDefault(o=>o.Name== QueryFilter)?.Value as Expression>; _shardingProvider = shardingProvider; _shardingRouteConfigOptions = shardingRouteConfigOptions; _virtualDataSourceRouteManager = virtualDataSourceRouteManager; _tableRouteManager = tableRouteManager; _entityMetadataManager = entityMetadataManager; - _jobManager = jobManager; } /// /// 初始化 @@ -117,10 +106,10 @@ namespace ShardingCore.Bootstrappers //检测校验分表分库对象元数据 entityMetadata.CheckShardingTableMetadata(); //添加任务 - if (virtualTableRoute is IJob routeJob && routeJob.AutoCreateTableByTime()) + if (virtualTableRoute is IJob routeJob) { var jobEntry = JobEntryFactory.Create(routeJob); - _jobManager.AddJob(jobEntry); + _shardingProvider.GetRequiredService().AddJob(jobEntry); } } entityMetadata.CheckGenericMetadata(); diff --git a/src/ShardingCore/Bootstrappers/IShardingBootstrapper.cs b/src/ShardingCore/Bootstrappers/IShardingBootstrapper.cs index 6d49a305..6a374b4e 100644 --- a/src/ShardingCore/Bootstrappers/IShardingBootstrapper.cs +++ b/src/ShardingCore/Bootstrappers/IShardingBootstrapper.cs @@ -7,13 +7,13 @@ namespace ShardingCore.Bootstrappers { /// - /// 主要的分表启动器 + /// 主要的分表初始化器,不再需要手动调用,IShardingRuntimeContext初始化的时候会调用 /// - public interface IShardingBootstrapper + internal interface IShardingBootstrapper { /// - /// 启动 + /// 初始化 /// - void Start(); + void Initialize(); } } \ No newline at end of file diff --git a/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs b/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs index 8650282b..758ea494 100644 --- a/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs +++ b/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs @@ -1,14 +1,19 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ShardingCore.Core; +using ShardingCore.Core.EntityMetadatas; +using ShardingCore.Core.ShardingConfigurations.Abstractions; +using ShardingCore.Exceptions; using ShardingCore.Extensions; using ShardingCore.Jobs; using ShardingCore.Jobs.Abstaractions; using ShardingCore.Logger; using ShardingCore.Sharding.MergeEngines.ParallelControl; +using ShardingCore.Sharding.ParallelTables; namespace ShardingCore.Bootstrappers { @@ -18,31 +23,38 @@ namespace ShardingCore.Bootstrappers * @Date: Monday, 21 December 2020 09:10:07 * @Email: 326308290@qq.com */ - public class ShardingBootstrapper : IShardingBootstrapper + internal class ShardingBootstrapper : IShardingBootstrapper { private readonly ILogger _logger; private readonly IShardingProvider _shardingProvider; - private readonly IShardingDbContextBootstrapper _shardingDbContextBootstrapper; + private readonly IShardingRouteConfigOptions _routeConfigOptions; + private readonly IEntityMetadataManager _entityMetadataManager; + private readonly IParallelTableManager _parallelTableManager; private readonly IJobManager _jobManager; private readonly DoOnlyOnce _doOnlyOnce = new DoOnlyOnce(); - public ShardingBootstrapper(IShardingProvider shardingProvider,IShardingDbContextBootstrapper shardingDbContextBootstrapper,IJobManager jobManager) + public ShardingBootstrapper(IShardingProvider shardingProvider) { _logger = InternalLoggerFactory.DefaultFactory.CreateLogger(); _shardingProvider = shardingProvider; - _shardingDbContextBootstrapper = shardingDbContextBootstrapper; - _jobManager = jobManager; + _routeConfigOptions = shardingProvider.GetRequiredService(); + _entityMetadataManager = shardingProvider.GetRequiredService(); + _parallelTableManager = shardingProvider.GetRequiredService(); + _jobManager = shardingProvider.GetRequiredService(); } /// - /// 启动 + /// 初始化 /// - public void Start() + public void Initialize() { if (!_doOnlyOnce.IsUnDo()) return; _logger.LogDebug("sharding core starting......"); - - _shardingDbContextBootstrapper.Initialize(); + + _logger.LogDebug("sharding core initialize entity metadata......"); + InitializeEntityMetadata(); + _logger.LogDebug("sharding core initialize parallel table......"); + InitializeParallelTables(); _logger.LogDebug($"sharding core complete init"); if (_jobManager != null && _jobManager.HasAnyJob()) @@ -54,6 +66,37 @@ namespace ShardingCore.Bootstrappers } _logger.LogDebug("sharding core running......"); } + + private void InitializeEntityMetadata() + { + var shardingEntities = _routeConfigOptions.GetShardingTableRouteTypes() + .Concat(_routeConfigOptions.GetShardingDataSourceRouteTypes()).ToHashSet(); + foreach (var entityType in shardingEntities) + { + var entityMetadataInitializerType = + typeof(EntityMetadataInitializer<>).GetGenericType0(entityType); + + var entityMetadataInitializer =(IEntityMetadataInitializer)_shardingProvider.CreateInstance(entityMetadataInitializerType); + entityMetadataInitializer.Initialize(); + + } + } + + private void InitializeParallelTables() + { + foreach (var parallelTableGroupNode in _routeConfigOptions.GetParallelTableGroupNodes()) + { + var parallelTableComparerType = parallelTableGroupNode.GetEntities() + .FirstOrDefault(o => !_entityMetadataManager.IsShardingTable(o.Type)); + if (parallelTableComparerType != null) + { + throw new ShardingCoreInvalidOperationException( + $"{parallelTableComparerType.Type.Name} must is sharding table type"); + } + + _parallelTableManager.AddParallelTable(parallelTableGroupNode); + } + } } } \ No newline at end of file diff --git a/src/ShardingCore/Bootstrappers/ShardingDbContextBootstrapper.cs b/src/ShardingCore/Bootstrappers/ShardingDbContextBootstrapper.cs deleted file mode 100644 index abb6df18..00000000 --- a/src/ShardingCore/Bootstrappers/ShardingDbContextBootstrapper.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Linq; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; -using ShardingCore.Core; -using ShardingCore.Core.EntityMetadatas; -using ShardingCore.Core.ShardingConfigurations.Abstractions; -using ShardingCore.Core.VirtualDatabase.VirtualDataSources; -using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions; -using ShardingCore.Exceptions; -using ShardingCore.Extensions; -using ShardingCore.Sharding.Abstractions; -using ShardingCore.Sharding.ParallelTables; - -/* -* @Author: xjm -* @Description: -* @Date: 2021/9/20 14:04:55 -* @Ver: 1.0 -* @Email: 326308290@qq.com -*/ -namespace ShardingCore.Bootstrappers -{ - /// - /// 分片具体DbContext初始化器 - /// - public interface IShardingDbContextBootstrapper - { - /// - /// 初始化 - /// - void Initialize(); - } - - /// - /// 分片具体DbContext初始化器 - /// - public class ShardingDbContextBootstrapper: IShardingDbContextBootstrapper - { - private readonly IShardingProvider _shardingProvider; - private readonly IShardingRouteConfigOptions _routeConfigOptions; - private readonly IEntityMetadataManager _entityMetadataManager; - private readonly IParallelTableManager _parallelTableManager; - - - - public ShardingDbContextBootstrapper( - IShardingProvider shardingProvider, - IShardingRouteConfigOptions routeConfigOptions, - IEntityMetadataManager entityMetadataManager, - IParallelTableManager parallelTableManager - ) - { - _shardingProvider = shardingProvider; - _routeConfigOptions = routeConfigOptions; - _entityMetadataManager = entityMetadataManager; - _parallelTableManager = parallelTableManager; - } - - /// - /// 初始化 - /// - public void Initialize() - { - InitializeEntityMetadata(); - InitializeParallelTables(); - // InitializeConfigure(); - } - - private void InitializeEntityMetadata() - { - var shardingEntities = _routeConfigOptions.GetShardingTableRouteTypes() - .Concat(_routeConfigOptions.GetShardingDataSourceRouteTypes()).ToHashSet(); - foreach (var entityType in shardingEntities) - { - var entityMetadataInitializerType = - typeof(EntityMetadataInitializer<>).GetGenericType0(entityType); - - var entityMetadataInitializer =(IEntityMetadataInitializer)_shardingProvider.CreateInstance(entityMetadataInitializerType); - entityMetadataInitializer.Initialize(); - - } - } - - private void InitializeParallelTables() - { - foreach (var parallelTableGroupNode in _routeConfigOptions.GetParallelTableGroupNodes()) - { - var parallelTableComparerType = parallelTableGroupNode.GetEntities() - .FirstOrDefault(o => !_entityMetadataManager.IsShardingTable(o.Type)); - if (parallelTableComparerType != null) - { - throw new ShardingCoreInvalidOperationException( - $"{parallelTableComparerType.Type.Name} must is sharding table type"); - } - - _parallelTableManager.AddParallelTable(parallelTableGroupNode); - } - } - - // private void InitializeConfigure() - // { - // var allVirtualDataSources = _virtualDataSourceManager.GetAllVirtualDataSources(); - // foreach (var virtualDataSource in allVirtualDataSources) - // { - // var dataSources = virtualDataSource.GetDataSources(); - // foreach (var dataSourceKv in dataSources) - // { - // var dataSourceName = dataSourceKv.Key; - // _dataSourceInitializer.InitConfigure(virtualDataSource, dataSourceName); - // } - // } - // } - } -} \ No newline at end of file diff --git a/src/ShardingCore/Core/IShardingProvider.cs b/src/ShardingCore/Core/IShardingProvider.cs index 17cadbdb..0fd604ff 100644 --- a/src/ShardingCore/Core/IShardingProvider.cs +++ b/src/ShardingCore/Core/IShardingProvider.cs @@ -6,5 +6,9 @@ namespace ShardingCore.Core public interface IShardingProvider { object GetService(Type serviceType); + + TService GetService(); + object GetRequiredService(Type serviceType); + TService GetRequiredService(); } } \ No newline at end of file diff --git a/src/ShardingCore/Core/ShardingConfigurations/Abstractions/IShardingRouteConfigOptions.cs b/src/ShardingCore/Core/ShardingConfigurations/Abstractions/IShardingRouteConfigOptions.cs index 86677bb1..042fb986 100644 --- a/src/ShardingCore/Core/ShardingConfigurations/Abstractions/IShardingRouteConfigOptions.cs +++ b/src/ShardingCore/Core/ShardingConfigurations/Abstractions/IShardingRouteConfigOptions.cs @@ -9,77 +9,98 @@ using System.Data.Common; namespace ShardingCore.Core.ShardingConfigurations.Abstractions { public interface IShardingRouteConfigOptions - { - /// - /// 当查询遇到没有路由被命中时是否抛出错误 - /// - bool ThrowIfQueryRouteNotMatch { get; set; } - // /// - // /// 如果数据库不存在就创建并且创建表除了分表的 - // /// - // bool EnsureCreatedWithOutShardingTable { get; set; } - // - // /// - // /// 是否需要在启动时创建分表 - // /// - // bool? CreateShardingTableOnStart { get; set; } - // /// - // /// 是否在启动时创建数据库 - // /// - // public bool? CreateDataBaseOnlyOnStart { get; set; } - /// - /// 忽略建表时的错误 - /// - bool? IgnoreCreateTableError { get; set; } - // ///// - // ///// 是否启用分表路由编译缓存(默认只缓存单个操作的也就是,>=,<,<=]]>) - // ///// default cache single filter route expression, ,>=,<,<=]]> with sharding property - // ///// - // //bool? EnableTableRouteCompileCache { get; set; } - // ///// - // ///// 是否启用分库路由编译缓存(默认只缓存单个操作的也就是,>=,<,<=]]>) - // ///// default cache single filter route expression, ,>=,<,<=]]> with sharding property - // ///// - // //bool? EnableDataSourceRouteCompileCache { get; set; } + { + /// + /// 当查询遇到没有路由被命中时是否抛出错误 + /// + bool ThrowIfQueryRouteNotMatch { get; set; } + + // /// + // /// 如果数据库不存在就创建并且创建表除了分表的 + // /// + // bool EnsureCreatedWithOutShardingTable { get; set; } + // + // /// + // /// 是否需要在启动时创建分表 + // /// + // bool? CreateShardingTableOnStart { get; set; } + // /// + // /// 是否在启动时创建数据库 + // /// + // public bool? CreateDataBaseOnlyOnStart { get; set; } + /// + /// 忽略建表时的错误 + /// + bool? IgnoreCreateTableError { get; set; } + + // ///// + // ///// 是否启用分表路由编译缓存(默认只缓存单个操作的也就是,>=,<,<=]]>) + // ///// default cache single filter route expression, ,>=,<,<=]]> with sharding property + // ///// + // //bool? EnableTableRouteCompileCache { get; set; } + // ///// + // ///// 是否启用分库路由编译缓存(默认只缓存单个操作的也就是,>=,<,<=]]>) + // ///// default cache single filter route expression, ,>=,<,<=]]> with sharding property + // ///// + // //bool? EnableDataSourceRouteCompileCache { get; set; } + /// + /// 添加分库路由 + /// + /// + void AddShardingDataSourceRoute() where TRoute : IVirtualDataSourceRoute; + /// /// 添加分库路由 /// /// void AddShardingDataSourceRoute(Type routeType); + + /// + /// 添加分表路由 + /// + /// + void AddShardingTableRoute() where TRoute : IVirtualTableRoute; + /// /// 添加分表路由 /// /// void AddShardingTableRoute(Type routeType); + /// /// 是否有虚拟表路由 /// /// /// bool HasVirtualTableRoute(Type entityType); + /// /// 获取虚拟表路由 /// /// /// Type GetVirtualTableRouteType(Type entityType); + /// /// 是否有虚拟库路由 /// /// /// bool HasVirtualDataSourceRoute(Type entityType); + /// /// 获取虚拟库路由 /// /// /// Type GetVirtualDataSourceRouteType(Type entityType); + /// /// 获取所有的分表路由类型 /// /// ISet GetShardingTableRouteTypes(); + /// /// 获取所有的分库路由类型 /// @@ -90,6 +111,7 @@ namespace ShardingCore.Core.ShardingConfigurations.Abstractions /// 平行表 /// bool AddParallelTableGroupNode(ParallelTableGroupNode parallelTableGroupNode); + /// /// 获取平行表 /// @@ -108,5 +130,7 @@ namespace ShardingCore.Core.ShardingConfigurations.Abstractions // // void UseExecutorDbContextConfigure(Action executorDbContextConfigure); // void UseShellDbContextConfigure(Action shellDbContextConfigure); + + } -} +} \ No newline at end of file diff --git a/src/ShardingCore/Core/ShardingConfigurations/ConfigBuilders/ShardingCoreConfigBuilder.cs b/src/ShardingCore/Core/ShardingConfigurations/ConfigBuilders/ShardingCoreConfigBuilder.cs index 13993cdc..b7f5ba08 100644 --- a/src/ShardingCore/Core/ShardingConfigurations/ConfigBuilders/ShardingCoreConfigBuilder.cs +++ b/src/ShardingCore/Core/ShardingConfigurations/ConfigBuilders/ShardingCoreConfigBuilder.cs @@ -1,132 +1,73 @@ -// using System; -// using System.Collections.Generic; -// using System.Linq; -// using Microsoft.EntityFrameworkCore; -// using Microsoft.Extensions.DependencyInjection; -// using ShardingCore.Core; -// using ShardingCore.Core.ShardingConfigurations; -// using ShardingCore.Core.ShardingConfigurations.ConfigBuilders; -// using ShardingCore.Core.VirtualDatabase.VirtualDataSources; -// using ShardingCore.Exceptions; -// using ShardingCore.Sharding.Abstractions; -// using ShardingCore.Sharding.ParallelTables; -// -// namespace ShardingCore.DIExtensions -// { -// /* -// * @Author: xjm -// * @Description: -// * @Date: 2021/9/19 20:49:03 -// * @Ver: 1.0 -// * @Email: 326308290@qq.com -// */ -// public class ShardingCoreConfigBuilder where TShardingDbContext:DbContext,IShardingDbContext -// { -// public IServiceCollection Services { get; } -// -// -// public List ShardingConfigOptions { get; } -// public ShardingRouteConfigOptions ShardingRouteConfigOptions { get; } -// -// -// public ShardingCoreConfigBuilder(IServiceCollection services) -// { -// Services = services; -// ShardingConfigOptions = new List(); -// ShardingRouteConfigOptions = new ShardingRouteConfigOptions(); -// } -// -// public ShardingConfigBuilder AddEntityConfig(Action entityConfigure) -// { -// entityConfigure?.Invoke(ShardingRouteConfigOptions); -// return new ShardingConfigBuilder(this); -// } -// //public ShardingCoreConfigBuilder AddDefaultDataSource(string dataSourceName, string connectionString) -// //{ -// // if (!string.IsNullOrWhiteSpace(defaultDataSourceName) || !string.IsNullOrWhiteSpace(defaultConnectionString)) -// // throw new ShardingCoreInvalidOperationException($"{nameof(AddDefaultDataSource)}-{dataSourceName}"); -// // this.defaultDataSourceName = dataSourceName; -// // this.defaultConnectionString = connectionString; -// // return this; -// //} -// -// //public ShardingCoreConfigBuilder AddDataSource(string dataSourceName, string connectionString) -// //{ -// // if (_dataSources.ContainsKey(dataSourceName)) -// // throw new ShardingCoreInvalidOperationException($"{nameof(AddDataSource)}-{dataSourceName} repeat"); -// // _dataSources.Add(dataSourceName, connectionString); -// // return this; -// //} -// } -// -// public class ShardingCoreBeginOptions -// { -// /// -// /// 配置id -// /// -// public string ConfigId { get; set; } -// /// -// /// 优先级 -// /// -// public int Priority { get; set; } -// /// -// /// 如果数据库不存在就创建并且创建表除了分表的 -// /// -// public bool EnsureCreatedWithOutShardingTable { get; set; } -// -// /// -// /// 是否需要在启动时创建分表 -// /// -// public bool? CreateShardingTableOnStart { get; set; } -// ///// -// ///// 是否自动追踪实体 -// ///// 譬如本次查询涉及到a1,a2,a3这三张表,会创建3个dbcontext进行查询,如果AutoTrackEntity=false那么针对被创建的dbcontext不会有任何变化,还是以追踪的形式查询 -// ///// 因为会同时创建3个dbcontext所以针对跨表查询完成后dbcontext会被回收,但是查询还是按原先的行为查询,所以如果不启用建议在查询的时候使用notracking -// ///// 如果AutoTrackEntity=true,那么被创建的三个dbcontext还是以原先的表现行为进行查询,在查询完成后会再次各自创建对应的dbcontext进行对象的追踪 -// ///// -// //public bool AutoTrackEntity { get; set; } -// /// -// /// 当查询遇到没有路由被命中时是否抛出错误 -// /// -// public bool ThrowIfQueryRouteNotMatch { get; set; } = true; -// -// /// -// /// 忽略建表时的错误 -// /// -// public bool? IgnoreCreateTableError { get; set; } = true; -// public int MaxQueryConnectionsLimit { get; set; } = Environment.ProcessorCount; -// public ConnectionModeEnum ConnectionMode { get; set; } = ConnectionModeEnum.SYSTEM_AUTO; -// public bool? EnableTableRouteCompileCache { get; set; } -// public bool? EnableDataSourceRouteCompileCache { get; set; } -// -// private readonly ISet _createTableEntities = new HashSet(); -// -// public void AddEntitiesTryCreateTable(params Type[] entityTypes) -// { -// foreach (var entityType in entityTypes) -// { -// _createTableEntities.Add(entityType); -// } -// -// } -// -// public ISet GetCreateTableEntities() -// { -// return _createTableEntities; -// } -// -// public readonly ISet _parallelTables = new HashSet(); -// -// public bool AddParallelTables(params Type[] types) -// { -// if (types.Length <= 0) -// throw new ShardingCoreInvalidOperationException( -// $"{nameof(AddParallelTables)} args :[{string.Join(",", types.Select(o => o.Name))}] should more than one length"); -// return _parallelTables.Add(new ParallelTableGroupNode(types.Select(o => new ParallelTableComparerType(o)))); -// } -// public ISet GetParallelTableGroupNodes() -// { -// return _parallelTables; -// } -// } -// } +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using ShardingCore.Core.ShardingConfigurations.Abstractions; +using ShardingCore.Sharding.Abstractions; + +namespace ShardingCore.Core.ShardingConfigurations.ConfigBuilders +{ + /* + * @Author: xjm + * @Description: + * @Date: 2021/9/19 20:49:03 + * @Ver: 1.0 + * @Email: 326308290@qq.com + */ + public class ShardingCoreConfigBuilder where TShardingDbContext:DbContext,IShardingDbContext + { + private readonly IServiceCollection _services; + + + private readonly ShardingRuntimeBuilder _shardingRuntimeBuilder; + + public ShardingCoreConfigBuilder(IServiceCollection services) + { + _services = services; + _shardingRuntimeBuilder = new ShardingRuntimeBuilder(); + } + + [Obsolete("plz use UseRouteConfig")] + public ShardingCoreConfigBuilder AddEntityConfig(Action entityConfigure) + { + _shardingRuntimeBuilder.UseRouteConfig(entityConfigure); + return this; + } + public ShardingCoreConfigBuilder UseRouteConfig(Action routeConfigure) + { + _shardingRuntimeBuilder.UseRouteConfig(routeConfigure); + return this; + } + public ShardingCoreConfigBuilder UseRouteConfig(Action routeConfigure) + { + _shardingRuntimeBuilder.UseRouteConfig(routeConfigure); + return this; + } + [Obsolete("plz use UseConfig")] + public ShardingCoreConfigBuilder AddConfig(Action shardingConfigure) + { + _shardingRuntimeBuilder.UseConfig(shardingConfigure); + return this; + } + public ShardingCoreConfigBuilder UseConfig(Action shardingConfigure) + { + _shardingRuntimeBuilder.UseConfig(shardingConfigure); + return this; + } + public ShardingCoreConfigBuilder UseConfig(Action shardingConfigure) + { + _shardingRuntimeBuilder.UseConfig(shardingConfigure); + return this; + } + + [Obsolete("plz use AddShardingCore")] + public void EnsureConfig() + { + _services.AddSingleton(sp => _shardingRuntimeBuilder.Build(sp)); + } + public void AddShardingCore() + { + _services.AddSingleton(sp => _shardingRuntimeBuilder.Build(sp)); + } + + } +} diff --git a/src/ShardingCore/Core/ShardingConfigurations/ShardingConfigOptions.cs b/src/ShardingCore/Core/ShardingConfigurations/ShardingConfigOptions.cs index 173927e0..db688e85 100644 --- a/src/ShardingCore/Core/ShardingConfigurations/ShardingConfigOptions.cs +++ b/src/ShardingCore/Core/ShardingConfigurations/ShardingConfigOptions.cs @@ -151,6 +151,26 @@ namespace ShardingCore.Core.ShardingConfigurations // throw new ArgumentNullException(nameof(tableEnsureManagerConfigure)); // } + public void CheckArguments() + { + if (string.IsNullOrWhiteSpace(DefaultDataSourceName)) + throw new ArgumentNullException( + $"{nameof(DefaultDataSourceName)} plz call {nameof(AddDefaultDataSource)}"); + + if (string.IsNullOrWhiteSpace(DefaultConnectionString)) + throw new ArgumentNullException( + $"{nameof(DefaultConnectionString)} plz call {nameof(AddDefaultDataSource)}"); + + if (ConnectionStringConfigure is null) + throw new ArgumentNullException($"plz call {nameof(UseShardingQuery)}"); + if (ConnectionConfigure is null ) + throw new ArgumentNullException( + $"plz call {nameof(UseShardingTransaction)}"); + + if (MaxQueryConnectionsLimit <= 0) + throw new ArgumentException( + $"{nameof(MaxQueryConnectionsLimit)} should greater than and equal 1"); + } } } diff --git a/src/ShardingCore/Core/ShardingConfigurations/ShardingRouteConfigOptions.cs b/src/ShardingCore/Core/ShardingConfigurations/ShardingRouteConfigOptions.cs index 7933572d..a6f7c7af 100644 --- a/src/ShardingCore/Core/ShardingConfigurations/ShardingRouteConfigOptions.cs +++ b/src/ShardingCore/Core/ShardingConfigurations/ShardingRouteConfigOptions.cs @@ -53,6 +53,15 @@ namespace ShardingCore.Core.ShardingConfigurations public bool ThrowIfQueryRouteNotMatch { get; set; } = true; + /// + /// 添加分库路由 + /// + /// + public void AddShardingDataSourceRoute() where TRoute : IVirtualDataSourceRoute + { + var routeType = typeof(TRoute); + AddShardingDataSourceRoute(routeType); + } public void AddShardingDataSourceRoute(Type routeType) { if (!routeType.IsVirtualDataSourceRoute()) @@ -71,6 +80,15 @@ namespace ShardingCore.Core.ShardingConfigurations _virtualDataSourceRoutes.Add(shardingEntityType, routeType); } } + /// + /// 添加分表路由 + /// + /// + public void AddShardingTableRoute() where TRoute : IVirtualTableRoute + { + var routeType = typeof(TRoute); + AddShardingTableRoute(routeType); + } public void AddShardingTableRoute(Type routeType) { if (!routeType.IsIVirtualTableRoute()) @@ -136,6 +154,7 @@ namespace ShardingCore.Core.ShardingConfigurations { return _parallelTables; } + // /// // /// 仅内部DbContext生效的配置委托 // /// @@ -156,5 +175,7 @@ namespace ShardingCore.Core.ShardingConfigurations // { // ShellDbContextConfigure = shellDbContextConfigure ?? throw new ArgumentNullException(nameof(shellDbContextConfigure)); // } + + } } diff --git a/src/ShardingCore/Core/ShardingProvider.cs b/src/ShardingCore/Core/ShardingProvider.cs index 65603ed9..e2e37438 100644 --- a/src/ShardingCore/Core/ShardingProvider.cs +++ b/src/ShardingCore/Core/ShardingProvider.cs @@ -29,5 +29,24 @@ namespace ShardingCore.Core } return service; } + public TService GetService() + { + return (TService)GetService(typeof(TService)); + } + public object GetRequiredService(Type serviceType) + { + var service = GetService(serviceType); + if (service == null) + { + throw new ArgumentNullException($"cant resolve {serviceType.FullName}"); + } + + return service; + } + + public TService GetRequiredService() + { + return (TService)GetRequiredService(typeof(TService)); + } } } \ No newline at end of file diff --git a/src/ShardingCore/Core/ShardingRuntimeContext.cs b/src/ShardingCore/Core/ShardingRuntimeContext.cs index 82201768..f28e1234 100644 --- a/src/ShardingCore/Core/ShardingRuntimeContext.cs +++ b/src/ShardingCore/Core/ShardingRuntimeContext.cs @@ -56,7 +56,7 @@ namespace ShardingCore.Core return; isInited = true; _serviceProvider = _serviceMap.BuildServiceProvider(); - _serviceProvider.GetRequiredService().Start(); + _serviceProvider.GetRequiredService().Initialize(); } } diff --git a/src/ShardingCore/Extensions/ShardingCoreConfigBuilderExtension.cs b/src/ShardingCore/Extensions/ShardingCoreConfigBuilderExtension.cs deleted file mode 100644 index 6b206a32..00000000 --- a/src/ShardingCore/Extensions/ShardingCoreConfigBuilderExtension.cs +++ /dev/null @@ -1,21 +0,0 @@ -// using System; -// using System.Collections.Generic; -// using System.Diagnostics.CodeAnalysis; -// using System.Linq; -// using System.Text; -// using System.Threading.Tasks; -// using Microsoft.EntityFrameworkCore; -// using ShardingCore.DIExtensions; -// using ShardingCore.Sharding.Abstractions; -// -// namespace ShardingCore.Extensions -// { -// public static class ShardingCoreConfigBuilderExtension -// { -// [ExcludeFromCodeCoverage] -// public static void AddEntityTryCreateTable(this ShardingCoreBeginOptions source) where TEntity:class -// { -// source.AddEntitiesTryCreateTable(typeof(TEntity)); -// } -// } -// } diff --git a/src/ShardingCore/Extensions/ShardingProviderExtension.cs b/src/ShardingCore/Extensions/ShardingProviderExtension.cs index 68ee2064..ac9264b6 100644 --- a/src/ShardingCore/Extensions/ShardingProviderExtension.cs +++ b/src/ShardingCore/Extensions/ShardingProviderExtension.cs @@ -33,25 +33,6 @@ namespace ShardingCore.Extensions return Activator.CreateInstance(serviceType, @params); } - public static object GetRequiredService(this IShardingProvider shardingProvider,Type serviceType) - { - var service = shardingProvider.GetService(serviceType); - if (service == null) - { - throw new ArgumentNullException($"cant resolve {serviceType.FullName}"); - } - return service; - } - - public static TService GetService(this IShardingProvider shardingProvider) - { - return (TService)shardingProvider.GetService(typeof(TService)); - } - - public static TService GetRequiredService(this IShardingProvider shardingProvider) - { - return (TService)shardingProvider.GetRequiredService(typeof(TService)); - } } } diff --git a/src/ShardingCore/Jobs/Abstaractions/IJob.cs b/src/ShardingCore/Jobs/Abstaractions/IJob.cs index 09932cd8..b2d12e02 100644 --- a/src/ShardingCore/Jobs/Abstaractions/IJob.cs +++ b/src/ShardingCore/Jobs/Abstaractions/IJob.cs @@ -8,6 +8,5 @@ namespace ShardingCore.Jobs.Abstaractions string JobName { get; } string[] GetCronExpressions(); Task ExecuteAsync(); - bool AutoCreateTableByTime(); } } diff --git a/src/ShardingCore/Jobs/Abstaractions/IJobManager.cs b/src/ShardingCore/Jobs/Abstaractions/IJobManager.cs index 7e76b1a3..14476d6e 100644 --- a/src/ShardingCore/Jobs/Abstaractions/IJobManager.cs +++ b/src/ShardingCore/Jobs/Abstaractions/IJobManager.cs @@ -11,7 +11,7 @@ namespace ShardingCore.Jobs.Abstaractions * @Date: Wednesday, 06 January 2021 13:10:13 * @Email: 326308290@qq.com */ - public interface IJobManager + internal interface IJobManager { void AddJob(JobEntry jobEntry); bool HasAnyJob(); diff --git a/src/ShardingCore/Jobs/JobRunnerService.cs b/src/ShardingCore/Jobs/JobRunnerService.cs index 542ee888..dc528814 100644 --- a/src/ShardingCore/Jobs/JobRunnerService.cs +++ b/src/ShardingCore/Jobs/JobRunnerService.cs @@ -18,7 +18,6 @@ namespace ShardingCore.Jobs [ExcludeFromCodeCoverage] internal class JobRunnerService { - private readonly IServiceProvider _serviceProvider; private readonly IJobManager _jobManager; private readonly ILogger _logger; private readonly CancellationTokenSource _cts = new CancellationTokenSource(); @@ -29,9 +28,8 @@ namespace ShardingCore.Jobs /// private const long MAX_DELAY_MILLIS = 30000L; - public JobRunnerService(IServiceProvider serviceProvider,IJobManager jobManager, ILogger logger) + public JobRunnerService(IJobManager jobManager, ILogger logger) { - _serviceProvider = serviceProvider; _jobManager = jobManager; _logger = logger; } diff --git a/src/ShardingCore/ShardingCoreExtension.cs b/src/ShardingCore/ShardingCoreExtension.cs index ecc05434..0d2a9fe4 100644 --- a/src/ShardingCore/ShardingCoreExtension.cs +++ b/src/ShardingCore/ShardingCoreExtension.cs @@ -29,6 +29,7 @@ using ShardingCore.Bootstrappers; using ShardingCore.Core; using ShardingCore.Core.DbContextCreator; using ShardingCore.Core.QueryTrackers; +using ShardingCore.Core.ShardingConfigurations.ConfigBuilders; using ShardingCore.Core.UnionAllMergeShardingProviders; using ShardingCore.Core.UnionAllMergeShardingProviders.Abstractions; using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions; @@ -55,34 +56,34 @@ namespace ShardingCore */ public static class ShardingCoreExtension { - // /// - // /// 添加ShardingCore配置和EntityFrameworkCore的]]> - // /// - // /// - // /// - // /// - // /// - // /// - // /// - // public static ShardingCoreConfigBuilder AddShardingDbContext(this IServiceCollection services, - // ServiceLifetime contextLifetime = ServiceLifetime.Scoped, - // ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) - // where TShardingDbContext : DbContext, IShardingDbContext - // { - // if (contextLifetime == ServiceLifetime.Singleton) - // throw new NotSupportedException($"{nameof(contextLifetime)}:{nameof(ServiceLifetime.Singleton)}"); - // if (optionsLifetime == ServiceLifetime.Singleton) - // throw new NotSupportedException($"{nameof(optionsLifetime)}:{nameof(ServiceLifetime.Singleton)}"); - // services.AddDbContext(UseDefaultSharding, contextLifetime, optionsLifetime); - // return services.AddShardingConfigure(); - // } - // - // public static ShardingCoreConfigBuilder AddShardingConfigure(this IServiceCollection services) - // where TShardingDbContext : DbContext, IShardingDbContext - // { - // //ShardingCoreHelper.CheckContextConstructors(); - // return new ShardingCoreConfigBuilder(services); - // } + /// + /// 添加ShardingCore配置和EntityFrameworkCore的]]> + /// + /// + /// + /// + /// + /// + /// + public static ShardingCoreConfigBuilder AddShardingDbContext(this IServiceCollection services, + ServiceLifetime contextLifetime = ServiceLifetime.Scoped, + ServiceLifetime optionsLifetime = ServiceLifetime.Scoped) + where TShardingDbContext : DbContext, IShardingDbContext + { + if (contextLifetime == ServiceLifetime.Singleton) + throw new NotSupportedException($"{nameof(contextLifetime)}:{nameof(ServiceLifetime.Singleton)}"); + if (optionsLifetime == ServiceLifetime.Singleton) + throw new NotSupportedException($"{nameof(optionsLifetime)}:{nameof(ServiceLifetime.Singleton)}"); + services.AddDbContext(UseDefaultSharding, contextLifetime, optionsLifetime); + return services.AddShardingConfigure(); + } + + public static ShardingCoreConfigBuilder AddShardingConfigure(this IServiceCollection services) + where TShardingDbContext : DbContext, IShardingDbContext + { + //ShardingCoreHelper.CheckContextConstructors(); + return new ShardingCoreConfigBuilder(services); + } public static void UseDefaultSharding(IServiceProvider serviceProvider,DbContextOptionsBuilder dbContextOptionsBuilder) where TShardingDbContext : DbContext, IShardingDbContext { @@ -106,12 +107,12 @@ namespace ShardingCore internal static IServiceCollection AddInternalShardingCore(this IServiceCollection services) where TShardingDbContext : DbContext, IShardingDbContext { services.TryAddSingleton(); - services.TryAddSingleton(); services.TryAddSingleton(); //分表dbcontext创建 services.TryAddSingleton>(); + // services.TryAddSingleton, DataSourceInitializer>(); services.TryAddSingleton(); services.TryAddSingleton(); diff --git a/src/ShardingCore/ShardingRuntimeBuilder.cs b/src/ShardingCore/ShardingRuntimeBuilder.cs index 4e297607..6413968c 100644 --- a/src/ShardingCore/ShardingRuntimeBuilder.cs +++ b/src/ShardingCore/ShardingRuntimeBuilder.cs @@ -11,44 +11,42 @@ namespace ShardingCore { public class ShardingRuntimeBuilder where TShardingDbContext : DbContext, IShardingDbContext { - private IShardingRouteConfigOptions _shardingRouteConfigOptions = new ShardingRouteConfigOptions(); - private ShardingConfigOptions _shardingConfigOptions = new ShardingConfigOptions(); - public ShardingRuntimeBuilder() - { - - } - + + private Action _shardingRouteConfigOptionsConfigure; public ShardingRuntimeBuilder UseRouteConfig(Action configure) { if (configure == null) throw new ArgumentNullException($"{nameof(configure)}"); - configure.Invoke(_shardingRouteConfigOptions); + Action fullConfigure = (sp, options) => + { + configure.Invoke(options); + }; + return UseRouteConfig(fullConfigure); + } + + public ShardingRuntimeBuilder UseRouteConfig(Action configure) + { + _shardingRouteConfigOptionsConfigure = configure ?? throw new ArgumentNullException($"{nameof(configure)}"); return this; } + private Action _shardingConfigOptionsConfigure; public ShardingRuntimeBuilder UseConfig(Action configure) { if (configure == null) throw new ArgumentNullException($"{nameof(configure)}"); - configure.Invoke(_shardingConfigOptions); - if (string.IsNullOrWhiteSpace(_shardingConfigOptions.DefaultDataSourceName)) - throw new ArgumentNullException( - $"{nameof(_shardingConfigOptions.DefaultDataSourceName)} plz call {nameof(ShardingConfigOptions.AddDefaultDataSource)}"); - - if (string.IsNullOrWhiteSpace(_shardingConfigOptions.DefaultConnectionString)) - throw new ArgumentNullException( - $"{nameof(_shardingConfigOptions.DefaultConnectionString)} plz call {nameof(ShardingConfigOptions.AddDefaultDataSource)}"); - - if (_shardingConfigOptions.ConnectionStringConfigure is null) - throw new ArgumentNullException($"plz call {nameof(_shardingConfigOptions.UseShardingQuery)}"); - if (_shardingConfigOptions.ConnectionConfigure is null ) - throw new ArgumentNullException( - $"plz call {nameof(_shardingConfigOptions.UseShardingTransaction)}"); - - if (_shardingConfigOptions.MaxQueryConnectionsLimit <= 0) - throw new ArgumentException( - $"{nameof(_shardingConfigOptions.MaxQueryConnectionsLimit)} should greater than and equal 1"); + Action fullConfigure = (sp, options) => + { + configure.Invoke(options); + }; + return UseConfig(fullConfigure); + } + public ShardingRuntimeBuilder UseConfig(Action configure) + { + if (configure == null) + throw new ArgumentNullException($"{nameof(configure)}"); + _shardingConfigOptionsConfigure = configure; return this; } @@ -68,9 +66,22 @@ namespace ShardingCore shardingRuntimeContext.AddServiceConfig(services => { // services.AddSingleton(sp => new DbContextTypeCollector()); - services.AddSingleton(sp => _shardingRouteConfigOptions); + services.AddSingleton(sp => + { + var shardingProvider = sp.GetRequiredService(); + var shardingRouteConfigOptions = new ShardingRouteConfigOptions(); + _shardingRouteConfigOptionsConfigure?.Invoke(shardingProvider,shardingRouteConfigOptions); + return shardingRouteConfigOptions; + }); - services.AddSingleton(sp => _shardingConfigOptions); + services.AddSingleton(sp => + { + var shardingProvider = sp.GetRequiredService(); + var shardingConfigOptions = new ShardingConfigOptions(); + _shardingConfigOptionsConfigure?.Invoke(shardingProvider,shardingConfigOptions); + shardingConfigOptions.CheckArguments(); + return shardingConfigOptions; + }); services.AddSingleton(sp => new ShardingProvider(sp,appServiceProvider)); services.AddInternalShardingCore(); }); diff --git a/src/ShardingCore/TableCreator/ShardingTableCreator.cs b/src/ShardingCore/TableCreator/ShardingTableCreator.cs index daf98331..46f44d5c 100644 --- a/src/ShardingCore/TableCreator/ShardingTableCreator.cs +++ b/src/ShardingCore/TableCreator/ShardingTableCreator.cs @@ -25,14 +25,11 @@ namespace ShardingCore.TableCreator private static readonly ILogger _logger = InternalLoggerFactory.CreateLogger(); - private readonly IServiceProvider _serviceProvider; private readonly IShardingRouteConfigOptions _routeConfigOptions; private readonly IRouteTailFactory _routeTailFactory; - public ShardingTableCreator(IServiceProvider serviceProvider, - IShardingRouteConfigOptions routeConfigOptions, IRouteTailFactory routeTailFactory) + public ShardingTableCreator(IShardingRouteConfigOptions routeConfigOptions, IRouteTailFactory routeTailFactory) { - _serviceProvider = serviceProvider; _routeConfigOptions = routeConfigOptions; _routeTailFactory = routeTailFactory; }