diff --git a/samples/Sample.MySql/Controllers/WeatherForecastController.cs b/samples/Sample.MySql/Controllers/WeatherForecastController.cs index bd9dae5b..07272913 100644 --- a/samples/Sample.MySql/Controllers/WeatherForecastController.cs +++ b/samples/Sample.MySql/Controllers/WeatherForecastController.cs @@ -1,74 +1,65 @@ -// using Microsoft.AspNetCore.Mvc; -// using Microsoft.Extensions.Logging; -// using System; -// using System.Collections.Generic; -// using System.Linq; -// using System.Threading.Tasks; -// using Microsoft.EntityFrameworkCore; -// using Sample.MySql.DbContexts; -// using Sample.MySql.Domain.Entities; -// using ShardingCore.Core.PhysicTables; -// using ShardingCore.Core.VirtualTables; -// using ShardingCore.DbContexts.VirtualDbContexts; -// using ShardingCore.Extensions; -// using ShardingCore.TableCreator; -// -// namespace Sample.MySql.Controllers -// { -// [ApiController] -// [Route("[controller]/[action]")] -// public class WeatherForecastController : ControllerBase -// { -// -// private readonly DefaultTableDbContext _defaultTableDbContext; -// private readonly IVirtualTableManager _virtualTableManager; -// private readonly IShardingTableCreator _tableCreator; -// -// public WeatherForecastController(DefaultTableDbContext defaultTableDbContext,IVirtualTableManager virtualTableManager, IShardingTableCreator tableCreator) -// { -// _defaultTableDbContext = defaultTableDbContext; -// _virtualTableManager = virtualTableManager; -// _tableCreator = tableCreator; -// } -// -// [HttpGet] -// public async Task Get() -// { -// var taleAllTails = _virtualTableManager.GetVirtualTable(typeof(SysUserLogByMonth)).GetTableAllTails(); -// -// -// var result = await _defaultTableDbContext.Set().AnyAsync(); -// var result1 = await _defaultTableDbContext.Set().Where(o => o.Id == "2" || o.Id == "3").ToShardingListAsync(); -// var result2 = await _defaultTableDbContext.Set().Skip(1).Take(10).ToShardingListAsync(); -// var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set().ShardingFirstOrDefaultAsync(); -// var shardingCountAsync = await _defaultTableDbContext.Set().ShardingCountAsync(); -// var shardingCountAsyn2c = _defaultTableDbContext.Set().ShardingCount(); -// -// return Ok(result1); -// } -// [HttpGet] -// public async Task Get1() -// { -// var allVirtualTables = _virtualTableManager.GetAllVirtualTables(); -// foreach (var virtualTable in allVirtualTables) -// { -// if (virtualTable.EntityType == typeof(SysUserLogByMonth)) -// { -// var now = DateTime.Now.Date.AddMonths(2); -// var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now); -// try -// { -// _virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail)); -// _tableCreator.CreateTable(tail); -// } -// catch (Exception e) -// { -// //ignore -// Console.WriteLine(e); -// } -// } -// } -// return Ok(); -// } -// } -// } +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Sample.MySql.DbContexts; +using Sample.MySql.Domain.Entities; +using ShardingCore.TableCreator; + +namespace Sample.MySql.Controllers +{ + [ApiController] + [Route("[controller]/[action]")] + public class WeatherForecastController : ControllerBase + { + + private readonly DefaultShardingDbContext _defaultTableDbContext; + + public WeatherForecastController(DefaultShardingDbContext defaultTableDbContext) + { + _defaultTableDbContext = defaultTableDbContext; + } + + [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(); + var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set().ToListAsync(); + var shardingCountAsync = await _defaultTableDbContext.Set().CountAsync(); + var shardingCountAsyn2c = _defaultTableDbContext.Set().Count(); + + return Ok(result1); + } + // [HttpGet] + // public async Task Get1() + // { + // var allVirtualTables = _virtualTableManager.GetAllVirtualTables(); + // foreach (var virtualTable in allVirtualTables) + // { + // if (virtualTable.EntityType == typeof(SysUserLogByMonth)) + // { + // var now = DateTime.Now.Date.AddMonths(2); + // var tail = virtualTable.GetVirtualRoute().ShardingKeyToTail(now); + // try + // { + // _virtualTableManager.AddPhysicTable(virtualTable, new DefaultPhysicTable(virtualTable, tail)); + // _tableCreator.CreateTable(tail); + // } + // catch (Exception e) + // { + // //ignore + // Console.WriteLine(e); + // } + // } + // } + // return Ok(); + // } + } +} diff --git a/samples/Sample.MySql/Sample.MySql.csproj b/samples/Sample.MySql/Sample.MySql.csproj index 597278a7..7d57ddf0 100644 --- a/samples/Sample.MySql/Sample.MySql.csproj +++ b/samples/Sample.MySql/Sample.MySql.csproj @@ -7,6 +7,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/samples/Sample.MySql/Shardings/SysUserModVirtualTableRoute.cs b/samples/Sample.MySql/Shardings/SysUserModVirtualTableRoute.cs index a73e8bc3..efa24e06 100644 --- a/samples/Sample.MySql/Shardings/SysUserModVirtualTableRoute.cs +++ b/samples/Sample.MySql/Shardings/SysUserModVirtualTableRoute.cs @@ -1,6 +1,5 @@ using Sample.MySql.Domain.Entities; using ShardingCore.Core.EntityMetadatas; -using ShardingCore.Core.PhysicTables; using ShardingCore.VirtualRoutes.Mods; namespace Sample.MySql.Shardings diff --git a/samples/Sample.MySql/Startup.cs b/samples/Sample.MySql/Startup.cs index 4d30701b..dda07471 100644 --- a/samples/Sample.MySql/Startup.cs +++ b/samples/Sample.MySql/Startup.cs @@ -1,16 +1,9 @@ -using Microsoft.AspNetCore.Builder; -using Microsoft.AspNetCore.Hosting; -using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Hosting; -using MySqlConnector; using Sample.MySql.DbContexts; using Sample.MySql.Shardings; using ShardingCore; -using ShardingCore.Helpers; -using ShardingCore.TableExists; +using ShardingCore.Core; +using ShardingCore.Extensions; namespace Sample.MySql { @@ -42,41 +35,72 @@ namespace Sample.MySql // op.AddShardingTableRoute(); // }); - services.AddShardingDbContext() - .AddEntityConfig(o => - { - o.CreateDataBaseOnlyOnStart = true; - o.CreateShardingTableOnStart = true; - o.EnsureCreatedWithOutShardingTable = true; - o.IgnoreCreateTableError = true; - o.AddShardingTableRoute(); - o.AddShardingTableRoute(); - o.AddShardingDataSourceRoute(); - o.UseShardingQuery((conStr, builder) => + services.AddSingleton(sp => + { + return new ShardingRuntimeBuilder() + .UseRouteConfig(o => { - builder.UseMySql(conStr, new MySqlServerVersion(new Version()) - ,b=>b.EnableRetryOnFailure() - ) - .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); - //builder.UseMySql(conStr, new MySqlServerVersion(new Version())); - }); - o.UseShardingTransaction((connection, builder) => - { - builder.UseMySql(connection, new MySqlServerVersion(new Version()) - ,b=>b.EnableRetryOnFailure() + o.AddShardingTableRoute(); + o.AddShardingTableRoute(); + // o.AddShardingDataSourceRoute(); + }).UseConfig(o => + { + o.UseShardingQuery((conStr,builder)=> + { + builder.UseMySql(conStr, new MySqlServerVersion(new Version()) + // ,b=>b.EnableRetryOnFailure() ) - .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); - }); - }) - .AddConfig(op => - { - op.ConfigId = "c0"; - op.AddDefaultDataSource("ds0", - "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); + .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); + }); + o.UseShardingTransaction((connection, builder) => + { + builder.UseMySql(connection, new MySqlServerVersion(new Version()) + // ,b=>b.EnableRetryOnFailure() + ) + .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); + }); + o.AddDefaultDataSource("ds0", + "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); - //op.AddDefaultDataSource("ds0", "server=127.0.0.1;port=3306;database=db2;userid=root;password=L6yBtV6qNENrwBy7;") - op.ReplaceTableEnsureManager(sp=>new MySqlTableEnsureManager()); - }).EnsureConfig(); + }) + .Build(sp); + }); + services.AddDbContext(ShardingCoreExtension.UseDefaultSharding); + // services.AddShardingDbContext() + // .AddEntityConfig(o => + // { + // o.CreateDataBaseOnlyOnStart = true; + // o.CreateShardingTableOnStart = true; + // o.EnsureCreatedWithOutShardingTable = true; + // o.IgnoreCreateTableError = true; + // o.AddShardingTableRoute(); + // o.AddShardingTableRoute(); + // o.AddShardingDataSourceRoute(); + // 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())); + // }); + // o.UseShardingTransaction((connection, builder) => + // { + // builder.UseMySql(connection, new MySqlServerVersion(new Version()) + // ,b=>b.EnableRetryOnFailure() + // ) + // .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking).UseLoggerFactory(efLogger); + // }); + // }) + // .AddConfig(op => + // { + // op.ConfigId = "c0"; + // op.AddDefaultDataSource("ds0", + // "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); + // + // //op.AddDefaultDataSource("ds0", "server=127.0.0.1;port=3306;database=db2;userid=root;password=L6yBtV6qNENrwBy7;") + // op.ReplaceTableEnsureManager(sp=>new MySqlTableEnsureManager()); + // }).EnsureConfig(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -88,20 +112,20 @@ 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.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/src/ShardingCore/Bootstrappers/EntityMetadataInitializer.cs b/src/ShardingCore/Bootstrappers/EntityMetadataInitializer.cs index 8f06960b..6ea54e67 100644 --- a/src/ShardingCore/Bootstrappers/EntityMetadataInitializer.cs +++ b/src/ShardingCore/Bootstrappers/EntityMetadataInitializer.cs @@ -1,11 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata; -using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using ShardingCore.Core; using ShardingCore.Core.EntityMetadatas; @@ -36,9 +29,9 @@ namespace ShardingCore.Bootstrappers /// /// /// - public class EntityMetadataInitializer: IEntityMetadataInitializer where TShardingDbContext:DbContext,IShardingDbContext where TEntity:class + public class EntityMetadataInitializer: IEntityMetadataInitializer where TEntity:class { - private static readonly ILogger> _logger=InternalLoggerFactory.CreateLogger>(); + private static readonly ILogger> _logger=InternalLoggerFactory.CreateLogger>(); // private const string QueryFilter = "QueryFilter"; // private readonly IEntityType _entityType; // private readonly string _virtualTableName; @@ -80,7 +73,7 @@ namespace ShardingCore.Bootstrappers /// public void Initialize() { - var entityMetadata = new EntityMetadata(_shardingEntityType, typeof(TShardingDbContext)); + var entityMetadata = new EntityMetadata(_shardingEntityType); if (!_entityMetadataManager.AddEntityMetadata(entityMetadata)) throw new ShardingCoreInvalidOperationException($"repeat add entity metadata {_shardingEntityType.FullName}"); //设置标签 @@ -105,9 +98,6 @@ namespace ShardingCore.Bootstrappers } if (_shardingRouteConfigOptions.TryGetVirtualTableRoute(out var virtualTableRouteType)) { - if (!typeof(TShardingDbContext).IsShardingTableDbContext()) - throw new ShardingCoreInvalidOperationException( - $"{typeof(TShardingDbContext)} is not impl {nameof(IShardingTableDbContext)},not support sharding table"); var entityMetadataTableBuilder = EntityMetadataTableBuilder.CreateEntityMetadataTableBuilder(entityMetadata); //配置属性分表信息 EntityMetadataHelper.Configure(entityMetadataTableBuilder); diff --git a/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs b/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs index 3646442d..8650282b 100644 --- a/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs +++ b/src/ShardingCore/Bootstrappers/ShardingBootstrapper.cs @@ -22,15 +22,15 @@ namespace ShardingCore.Bootstrappers { private readonly ILogger _logger; private readonly IShardingProvider _shardingProvider; - private readonly IDbContextTypeCollector _dbContextTypeCollector; + private readonly IShardingDbContextBootstrapper _shardingDbContextBootstrapper; private readonly IJobManager _jobManager; private readonly DoOnlyOnce _doOnlyOnce = new DoOnlyOnce(); - public ShardingBootstrapper(IShardingProvider shardingProvider,IDbContextTypeCollector dbContextTypeCollector,IJobManager jobManager) + public ShardingBootstrapper(IShardingProvider shardingProvider,IShardingDbContextBootstrapper shardingDbContextBootstrapper,IJobManager jobManager) { _logger = InternalLoggerFactory.DefaultFactory.CreateLogger(); _shardingProvider = shardingProvider; - _dbContextTypeCollector = dbContextTypeCollector; + _shardingDbContextBootstrapper = shardingDbContextBootstrapper; _jobManager = jobManager; } /// @@ -42,11 +42,8 @@ namespace ShardingCore.Bootstrappers return; _logger.LogDebug("sharding core starting......"); - var instanceType = typeof(ShardingDbContextBootstrapper<>).GetGenericType0(_dbContextTypeCollector.ShardingDbContextType); - var instance = (IShardingDbContextBootstrapper)_shardingProvider.CreateInstance(instanceType); - _logger.LogDebug($"{_dbContextTypeCollector.ShardingDbContextType} start init......"); - instance.Initialize(); - _logger.LogDebug($"{_dbContextTypeCollector.ShardingDbContextType} complete init"); + _shardingDbContextBootstrapper.Initialize(); + _logger.LogDebug($"sharding core complete init"); if (_jobManager != null && _jobManager.HasAnyJob()) { @@ -55,6 +52,7 @@ namespace ShardingCore.Bootstrappers await _shardingProvider.GetRequiredService().StartAsync(); }, TaskCreationOptions.LongRunning); } + _logger.LogDebug("sharding core running......"); } } diff --git a/src/ShardingCore/Bootstrappers/ShardingDbContextBootstrapper.cs b/src/ShardingCore/Bootstrappers/ShardingDbContextBootstrapper.cs index e5d77f3e..abb6df18 100644 --- a/src/ShardingCore/Bootstrappers/ShardingDbContextBootstrapper.cs +++ b/src/ShardingCore/Bootstrappers/ShardingDbContextBootstrapper.cs @@ -35,8 +35,7 @@ namespace ShardingCore.Bootstrappers /// /// 分片具体DbContext初始化器 /// - public class ShardingDbContextBootstrapper : IShardingDbContextBootstrapper - where TShardingDbContext : DbContext, IShardingDbContext + public class ShardingDbContextBootstrapper: IShardingDbContextBootstrapper { private readonly IShardingProvider _shardingProvider; private readonly IShardingRouteConfigOptions _routeConfigOptions; @@ -44,8 +43,6 @@ namespace ShardingCore.Bootstrappers private readonly IParallelTableManager _parallelTableManager; - // private readonly ITrackerManager _trackerManager; - private readonly Type _shardingDbContextType; public ShardingDbContextBootstrapper( IShardingProvider shardingProvider, @@ -54,7 +51,6 @@ namespace ShardingCore.Bootstrappers IParallelTableManager parallelTableManager ) { - _shardingDbContextType = typeof(TShardingDbContext); _shardingProvider = shardingProvider; _routeConfigOptions = routeConfigOptions; _entityMetadataManager = entityMetadataManager; @@ -78,7 +74,7 @@ namespace ShardingCore.Bootstrappers foreach (var entityType in shardingEntities) { var entityMetadataInitializerType = - typeof(EntityMetadataInitializer<,>).GetGenericType1(_shardingDbContextType, entityType); + typeof(EntityMetadataInitializer<>).GetGenericType0(entityType); var entityMetadataInitializer =(IEntityMetadataInitializer)_shardingProvider.CreateInstance(entityMetadataInitializerType); entityMetadataInitializer.Initialize(); diff --git a/src/ShardingCore/Core/EntityMetadatas/EntityMetadata.cs b/src/ShardingCore/Core/EntityMetadatas/EntityMetadata.cs index bb4be067..79a03cb6 100644 --- a/src/ShardingCore/Core/EntityMetadatas/EntityMetadata.cs +++ b/src/ShardingCore/Core/EntityMetadatas/EntityMetadata.cs @@ -16,10 +16,9 @@ namespace ShardingCore.Core.EntityMetadatas /// public class EntityMetadata {private const string QueryFilter = "QueryFilter"; - public EntityMetadata(Type entityType, Type shardingDbContextType) + public EntityMetadata(Type entityType) { EntityType = entityType; - ShardingDbContextType = shardingDbContextType; ShardingDataSourceProperties = new Dictionary(); ShardingTableProperties = new Dictionary(); } @@ -28,8 +27,6 @@ namespace ShardingCore.Core.EntityMetadatas /// public Type EntityType { get; } - public Type ShardingDbContextType { get; } - /// /// 是否多数据源 /// diff --git a/src/ShardingCore/Core/ShardingConfigurations/ShardingRouteConfigOptions.cs b/src/ShardingCore/Core/ShardingConfigurations/ShardingRouteConfigOptions.cs index a253ab60..7933572d 100644 --- a/src/ShardingCore/Core/ShardingConfigurations/ShardingRouteConfigOptions.cs +++ b/src/ShardingCore/Core/ShardingConfigurations/ShardingRouteConfigOptions.cs @@ -50,15 +50,6 @@ namespace ShardingCore.Core.ShardingConfigurations /// 忽略建表时的错误 /// public bool? IgnoreCreateTableError { get; set; } = false; - /// - /// 添加分表路由 - /// - /// - public void AddShardingDataSourceRoute() where TRoute : IVirtualDataSourceRoute - { - var routeType = typeof(TRoute); - AddShardingDataSourceRoute(routeType); - } public bool ThrowIfQueryRouteNotMatch { get; set; } = true; @@ -80,15 +71,6 @@ 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()) diff --git a/src/ShardingCore/Core/ShardingRuntimeContext.cs b/src/ShardingCore/Core/ShardingRuntimeContext.cs index 7cef505b..82201768 100644 --- a/src/ShardingCore/Core/ShardingRuntimeContext.cs +++ b/src/ShardingCore/Core/ShardingRuntimeContext.cs @@ -54,9 +54,9 @@ namespace ShardingCore.Core { if (isInited) return; + isInited = true; _serviceProvider = _serviceMap.BuildServiceProvider(); _serviceProvider.GetRequiredService().Start(); - isInited = true; } } @@ -126,6 +126,7 @@ namespace ShardingCore.Core lock (INIT_MODEL) { if(isInitModeled) return; + isInitModeled = true; var entityMetadataManager = GetService(); var entityTypes = dbContext.Model.GetEntityTypes(); foreach (var entityType in entityTypes) @@ -152,7 +153,7 @@ namespace ShardingCore.Core } private void CheckIfNotBuild() { - if (isInited) + if (!isInited) throw new InvalidOperationException("sharding runtime not init"); } diff --git a/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/DataSourceRouteRuleEngine.cs b/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/DataSourceRouteRuleEngine.cs index 2937f27c..c7ba3370 100644 --- a/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/DataSourceRouteRuleEngine.cs +++ b/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/DataSourceRouteRuleEngine.cs @@ -19,7 +19,7 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine * @Ver: 1.0 * @Email: 326308290@qq.com */ - public class DataSourceRouteRuleEngine : IDataSourceRouteRuleEngine where TShardingDbContext : DbContext, IShardingDbContext + public class DataSourceRouteRuleEngine: IDataSourceRouteRuleEngine { private readonly IEntityMetadataManager _entityMetadataManager; diff --git a/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/DataSourceRouteRuleEngineFactory.cs b/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/DataSourceRouteRuleEngineFactory.cs index 1622856d..d9cf1292 100644 --- a/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/DataSourceRouteRuleEngineFactory.cs +++ b/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/DataSourceRouteRuleEngineFactory.cs @@ -18,14 +18,14 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine /// /// 分库路由引擎工程 /// - public class DataSourceRouteRuleEngineFactory: IDataSourceRouteRuleEngineFactory where TShardingDbContext : DbContext, IShardingDbContext + public class DataSourceRouteRuleEngineFactory: IDataSourceRouteRuleEngineFactory { - private readonly IDataSourceRouteRuleEngine _dataSourceRouteRuleEngine; + private readonly IDataSourceRouteRuleEngine _dataSourceRouteRuleEngine; /// /// ctor /// /// - public DataSourceRouteRuleEngineFactory(IDataSourceRouteRuleEngine dataSourceRouteRuleEngine) + public DataSourceRouteRuleEngineFactory(IDataSourceRouteRuleEngine dataSourceRouteRuleEngine) { _dataSourceRouteRuleEngine = dataSourceRouteRuleEngine; } diff --git a/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/IDataSourceRouteRuleEngine.cs b/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/IDataSourceRouteRuleEngine.cs index c2b4b794..4fe60aa6 100644 --- a/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/IDataSourceRouteRuleEngine.cs +++ b/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/IDataSourceRouteRuleEngine.cs @@ -18,9 +18,4 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine DataSourceRouteResult Route(DataSourceRouteRuleContext routeRuleContext); } - public interface IDataSourceRouteRuleEngine : IDataSourceRouteRuleEngine - where TShardingDbContext : DbContext, IShardingDbContext - { - - } } diff --git a/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/IDataSourceRouteRuleEngineFactory.cs b/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/IDataSourceRouteRuleEngineFactory.cs index eefbb3d1..a3a1360f 100644 --- a/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/IDataSourceRouteRuleEngineFactory.cs +++ b/src/ShardingCore/Core/VirtualRoutes/DataSourceRoutes/RouteRuleEngine/IDataSourceRouteRuleEngineFactory.cs @@ -20,8 +20,4 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine DataSourceRouteResult Route(IQueryable queryable, IShardingDbContext shardingDbContext, Dictionary queryEntities); //DataSourceRouteResult Route(DataSourceRouteRuleContext ruleContext); } - public interface IDataSourceRouteRuleEngineFactory : IDataSourceRouteRuleEngineFactory - where TShardingDbContext : DbContext, IShardingDbContext - { - } } diff --git a/src/ShardingCore/Core/VirtualRoutes/TableRoutes/RoutingRuleEngine/TableRouteRuleEngine.cs b/src/ShardingCore/Core/VirtualRoutes/TableRoutes/RoutingRuleEngine/TableRouteRuleEngine.cs index 790f233c..30d72012 100644 --- a/src/ShardingCore/Core/VirtualRoutes/TableRoutes/RoutingRuleEngine/TableRouteRuleEngine.cs +++ b/src/ShardingCore/Core/VirtualRoutes/TableRoutes/RoutingRuleEngine/TableRouteRuleEngine.cs @@ -89,6 +89,10 @@ namespace ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine if (tableRouteResults.IsNotEmpty()) { dataSourceCount++; + if (tableRouteResults.Count > 1) + { + isCrossTable = true; + } foreach (var tableRouteResult in tableRouteResults) { if (tableRouteResult.ReplaceTables.Count > 1) diff --git a/src/ShardingCore/EFCores/OptionsExtensions/ShardingOptionsExtension.cs b/src/ShardingCore/EFCores/OptionsExtensions/ShardingOptionsExtension.cs new file mode 100644 index 00000000..a395bab0 --- /dev/null +++ b/src/ShardingCore/EFCores/OptionsExtensions/ShardingOptionsExtension.cs @@ -0,0 +1,118 @@ +using System.Collections.Generic; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.Extensions.DependencyInjection; +using ShardingCore.Core; + +namespace ShardingCore.EFCores.OptionsExtensions +{ + + + /* + * @Author: xjm + * @Description: + * @Date: 2021/10/17 20:27:12 + * @Ver: 1.0 + * @Email: 326308290@qq.com + */ + +#if EFCORE6 + public class ShardingOptionsExtension : IDbContextOptionsExtension + { + private readonly IShardingRuntimeContext _shardingRuntimeContext; + + public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext) + { + _shardingRuntimeContext = shardingRuntimeContext; + } + public void ApplyServices(IServiceCollection services) + { + services.AddSingleton(sp => _shardingRuntimeContext); + } + + public void Validate(IDbContextOptions options) + { + } + + + public DbContextOptionsExtensionInfo Info => new ShardingWrapDbContextOptionsExtensionInfo(this); + + private class ShardingWrapDbContextOptionsExtensionInfo : DbContextOptionsExtensionInfo + { + public ShardingWrapDbContextOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + { + } + + public override int GetServiceProviderHashCode() => 0; + + public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => true; + + public override void PopulateDebugInfo(IDictionary debugInfo) + { + } + + public override bool IsDatabaseProvider => false; + public override string LogFragment => "ShardingOptionsExtension"; + } + } +#endif +#if EFCORE3 || EFCORE5 + + public class ShardingOptionsExtension: IDbContextOptionsExtension + { + private readonly IShardingRuntimeContext _shardingRuntimeContext; + + public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext) + { + _shardingRuntimeContext = shardingRuntimeContext; + } + public void ApplyServices(IServiceCollection services) + { + services.AddSingleton(sp => _shardingRuntimeContext); + } + + public void Validate(IDbContextOptions options) + { + } + + + public DbContextOptionsExtensionInfo Info => new ShardingWrapDbContextOptionsExtensionInfo(this); + + private class ShardingWrapDbContextOptionsExtensionInfo : DbContextOptionsExtensionInfo + { + public ShardingWrapDbContextOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) { } + + public override long GetServiceProviderHashCode() => 0; + + public override void PopulateDebugInfo(IDictionary debugInfo) { } + + public override bool IsDatabaseProvider => false; + public override string LogFragment => "ShardingOptionsExtension"; + } + } + +#endif +#if EFCORE2 + + public class ShardingOptionsExtension: IDbContextOptionsExtension + { + private readonly IShardingRuntimeContext _shardingRuntimeContext; + + public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext) + { + _shardingRuntimeContext = shardingRuntimeContext; + } + public bool ApplyServices(IServiceCollection services) + { + services.AddSingleton(sp => _shardingRuntimeContext); + return true; + } + public long GetServiceProviderHashCode() => 0; + + public void Validate(IDbContextOptions options) + { + } + + public string LogFragment => "ShardingOptionsExtension"; + } +#endif +} diff --git a/src/ShardingCore/EFCores/OptionsExtensions/ShardingWrapOptionsExtension.cs b/src/ShardingCore/EFCores/OptionsExtensions/ShardingWrapOptionsExtension.cs index 07e7a9f8..7e82462a 100644 --- a/src/ShardingCore/EFCores/OptionsExtensions/ShardingWrapOptionsExtension.cs +++ b/src/ShardingCore/EFCores/OptionsExtensions/ShardingWrapOptionsExtension.cs @@ -18,15 +18,12 @@ namespace ShardingCore.EFCores.OptionsExtensions #if EFCORE6 public class ShardingWrapOptionsExtension : IDbContextOptionsExtension { - private readonly IShardingRuntimeContext _shardingRuntimeContext; - public ShardingWrapOptionsExtension(IShardingRuntimeContext shardingRuntimeContext) + public ShardingWrapOptionsExtension() { - _shardingRuntimeContext = shardingRuntimeContext; } public void ApplyServices(IServiceCollection services) { - services.AddSingleton(sp => _shardingRuntimeContext); } public void Validate(IDbContextOptions options) diff --git a/src/ShardingCore/Extensions/ShardingRouteConfigOptionsExtension.cs b/src/ShardingCore/Extensions/ShardingRouteConfigOptionsExtension.cs new file mode 100644 index 00000000..0ea9a22c --- /dev/null +++ b/src/ShardingCore/Extensions/ShardingRouteConfigOptionsExtension.cs @@ -0,0 +1,30 @@ +using ShardingCore.Core.ShardingConfigurations.Abstractions; +using ShardingCore.Core.VirtualRoutes.DataSourceRoutes; +using ShardingCore.Core.VirtualRoutes.TableRoutes; + +namespace ShardingCore.Extensions +{ + + public static class ShardingRouteConfigOptionsExtension + { + + /// + /// 添加分表路由 + /// + /// + public static void AddShardingDataSourceRoute(this IShardingRouteConfigOptions options) where TRoute : IVirtualDataSourceRoute + { + var routeType = typeof(TRoute); + options.AddShardingDataSourceRoute(routeType); + } + /// + /// 添加分表路由 + /// + /// + public static void AddShardingTableRoute(this IShardingRouteConfigOptions options) where TRoute : IVirtualTableRoute + { + var routeType = typeof(TRoute); + options.AddShardingTableRoute(routeType); + } + } +} diff --git a/src/ShardingCore/Sharding/Abstractions/IStreamMergeContextFactory.cs b/src/ShardingCore/Sharding/Abstractions/IStreamMergeContextFactory.cs index de30a222..a99df950 100644 --- a/src/ShardingCore/Sharding/Abstractions/IStreamMergeContextFactory.cs +++ b/src/ShardingCore/Sharding/Abstractions/IStreamMergeContextFactory.cs @@ -16,7 +16,7 @@ namespace ShardingCore.Sharding.Abstractions StreamMergeContext Create(IMergeQueryCompilerContext mergeQueryCompilerContext); } - public interface IStreamMergeContextFactory : IStreamMergeContextFactory where TShardingDbContext:DbContext,IShardingDbContext - { - } + // public interface IStreamMergeContextFactory : IStreamMergeContextFactory where TShardingDbContext:DbContext,IShardingDbContext + // { + // } } \ No newline at end of file diff --git a/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs b/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs index d5c5d40c..4cc5de9a 100644 --- a/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs +++ b/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs @@ -82,6 +82,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors /// shell dbcontext最外面的壳 /// private readonly DbContext _shardingShellDbContext; + private readonly IShardingRuntimeContext _shardingRuntimeContext; /// /// 数据库事务 @@ -118,11 +119,13 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors IDbContextCreator dbContextCreator, ActualConnectionStringManager actualConnectionStringManager) { + var shardingDbContext = (IShardingDbContext)shardingShellDbContext; DataSourceName = dataSourceName; IsDefault = isDefault; _shardingShellDbContext = shardingShellDbContext; + _shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); DbContextType = shardingShellDbContext.GetType(); - _virtualDataSource =((IShardingDbContext)shardingShellDbContext) + _virtualDataSource =shardingDbContext .GetVirtualDataSource(); _dbContextCreator = dbContextCreator; _actualConnectionStringManager = actualConnectionStringManager; @@ -149,7 +152,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors try { //先创建dbcontext option builder - var dbContextOptionsBuilder = CreateDbContextOptionBuilder(DbContextType); + var dbContextOptionsBuilder = CreateDbContextOptionBuilder(DbContextType).UseShardingOptions(_shardingRuntimeContext); if (IsDefault) { diff --git a/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs b/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs index 26fd3b00..edd089fe 100644 --- a/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs +++ b/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs @@ -34,6 +34,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors //private readonly ConcurrentDictionary> _dbContextCaches = new ConcurrentDictionary>(); private readonly ConcurrentDictionary _dbContextCaches = new ConcurrentDictionary(); + private readonly IShardingRuntimeContext _shardingRuntimeContext; private readonly IVirtualDataSource _virtualDataSource; private readonly ITableRouteManager _tableRouteManager; private readonly IDbContextCreator _dbContextCreator; @@ -59,14 +60,14 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors { _shardingDbContext = shardingDbContext; //初始化 - var shardingRuntimeContext = shardingDbContext.GetRequireService(); - shardingRuntimeContext.GetOrCreateShardingRuntimeModel(shardingDbContext); - _virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); - _tableRouteManager = shardingRuntimeContext.GetTableRouteManager(); - _dbContextCreator = shardingRuntimeContext.GetDbContextCreator(); - _entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); - _routeTailFactory = shardingRuntimeContext.GetRouteTailFactory(); - var shardingReadWriteManager = shardingRuntimeContext.GetShardingReadWriteManager(); + _shardingRuntimeContext = shardingDbContext.GetRequireService(); + _shardingRuntimeContext.GetOrCreateShardingRuntimeModel(shardingDbContext); + _virtualDataSource = _shardingRuntimeContext.GetVirtualDataSource(); + _tableRouteManager = _shardingRuntimeContext.GetTableRouteManager(); + _dbContextCreator = _shardingRuntimeContext.GetDbContextCreator(); + _entityMetadataManager = _shardingRuntimeContext.GetEntityMetadataManager(); + _routeTailFactory = _shardingRuntimeContext.GetRouteTailFactory(); + var shardingReadWriteManager = _shardingRuntimeContext.GetShardingReadWriteManager(); _actualConnectionStringManager = new ActualConnectionStringManager(shardingReadWriteManager,_virtualDataSource); } @@ -104,7 +105,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors { var dbContextOptionBuilder = DataSourceDbContext.CreateDbContextOptionBuilder(_shardingDbContext.GetType()); var connectionString = _actualConnectionStringManager.GetConnectionString(dataSourceName, false); - _virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder); + _virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder).UseShardingOptions(_shardingRuntimeContext); return dbContextOptionBuilder.Options; } diff --git a/src/ShardingCore/Sharding/StreamMergeContextFactory.cs b/src/ShardingCore/Sharding/StreamMergeContextFactory.cs index b5755416..de08f598 100644 --- a/src/ShardingCore/Sharding/StreamMergeContextFactory.cs +++ b/src/ShardingCore/Sharding/StreamMergeContextFactory.cs @@ -18,7 +18,7 @@ namespace ShardingCore.Sharding * @Date: Thursday, 28 January 2021 16:52:43 * @Email: 326308290@qq.com */ - public class StreamMergeContextFactory : IStreamMergeContextFactory where TShardingDbContext:DbContext,IShardingDbContext + public class StreamMergeContextFactory : IStreamMergeContextFactory { private readonly IRouteTailFactory _routeTailFactory; private readonly IQueryableParseEngine _queryableParseEngine; diff --git a/src/ShardingCore/DIExtension.cs b/src/ShardingCore/ShardingCoreExtension.cs similarity index 70% rename from src/ShardingCore/DIExtension.cs rename to src/ShardingCore/ShardingCoreExtension.cs index 902614c2..ecc05434 100644 --- a/src/ShardingCore/DIExtension.cs +++ b/src/ShardingCore/ShardingCoreExtension.cs @@ -16,7 +16,6 @@ using ShardingCore.Core.VirtualRoutes; using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine; using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions; using ShardingCore.Core.VirtualRoutes.TableRoutes.RoutingRuleEngine; -using ShardingCore.DIExtensions; using ShardingCore.EFCores; using ShardingCore.EFCores.OptionsExtensions; using ShardingCore.Jobs; @@ -25,6 +24,7 @@ using ShardingCore.Sharding.Abstractions; using ShardingCore.Sharding.ShardingQueryExecutors; using ShardingCore.TableCreator; using System; +using System.Diagnostics; using ShardingCore.Bootstrappers; using ShardingCore.Core; using ShardingCore.Core.DbContextCreator; @@ -32,6 +32,8 @@ using ShardingCore.Core.QueryTrackers; using ShardingCore.Core.UnionAllMergeShardingProviders; using ShardingCore.Core.UnionAllMergeShardingProviders.Abstractions; using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions; +using ShardingCore.Core.VirtualRoutes.Abstractions; +using ShardingCore.Core.VirtualRoutes.TableRoutes; using ShardingCore.Sharding.MergeContexts; using ShardingCore.Sharding.ParallelTables; using ShardingCore.Sharding.Parsers; @@ -51,48 +53,60 @@ namespace ShardingCore * @Date: Thursday, 28 January 2021 13:32:18 * @Email: 326308290@qq.com */ - public static class DIExtension + 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 { var shardingRuntimeContext = serviceProvider.GetRequiredService(); + // Stopwatch sp=Stopwatch.StartNew(); + // for (int i = 0; i < 100000; i++) + // { + // + // var virtualDataSource1 = shardingRuntimeContext.GetVirtualDataSource(); + // + // } + // sp.Stop(); + // Console.WriteLine(sp.ElapsedMilliseconds); var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); var connectionString = virtualDataSource.GetConnectionString(virtualDataSource.DefaultDataSourceName); - var contextOptionsBuilder = virtualDataSource.ConfigurationParams.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder).UseSharding(shardingRuntimeContext); + var contextOptionsBuilder = virtualDataSource.ConfigurationParams.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder) + .UseSharding(shardingRuntimeContext); virtualDataSource.ConfigurationParams.UseShellDbContextOptionBuilder(contextOptionsBuilder); } internal static IServiceCollection AddInternalShardingCore(this IServiceCollection services) where TShardingDbContext : DbContext, IShardingDbContext { + services.TryAddSingleton(); + services.TryAddSingleton(); services.TryAddSingleton(); //分表dbcontext创建 services.TryAddSingleton>(); @@ -100,13 +114,13 @@ namespace ShardingCore // services.TryAddSingleton, DataSourceInitializer>(); services.TryAddSingleton(); - services.TryAddSingleton, StreamMergeContextFactory>(); + services.TryAddSingleton(); services.TryAddSingleton(); //虚拟数据源管理 services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton, DataSourceRouteRuleEngine>(); - services.TryAddSingleton, DataSourceRouteRuleEngineFactory>(); + services.TryAddSingleton(); + services.TryAddSingleton(); //读写分离链接创建工厂 services.TryAddSingleton(); services.TryAddSingleton(); @@ -155,24 +169,33 @@ namespace ShardingCore } public static DbContextOptionsBuilder UseSharding(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext) where TShardingDbContext : DbContext, IShardingDbContext { - return optionsBuilder.UseShardingWrapMark(shardingRuntimeContext) + return optionsBuilder.UseShardingWrapMark().UseShardingOptions(shardingRuntimeContext) .ReplaceService() .ReplaceService() .ReplaceService>() .ReplaceService>(); } - - - private static DbContextOptionsBuilder UseShardingWrapMark(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext) + public static DbContextOptionsBuilder UseShardingOptions(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext) { - var extension = optionsBuilder.CreateOrGetExtension(shardingRuntimeContext); - ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(extension); + var shardingOptionsExtension = optionsBuilder.CreateOrGetShardingOptionsExtension(shardingRuntimeContext); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(shardingOptionsExtension); return optionsBuilder; } - private static ShardingWrapOptionsExtension CreateOrGetExtension(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext) + + private static DbContextOptionsBuilder UseShardingWrapMark(this DbContextOptionsBuilder optionsBuilder) + { + var shardingWrapExtension = optionsBuilder.CreateOrGetShardingWrapExtension(); + ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(shardingWrapExtension); + return optionsBuilder; + } + + private static ShardingWrapOptionsExtension CreateOrGetShardingWrapExtension(this DbContextOptionsBuilder optionsBuilder) => optionsBuilder.Options.FindExtension() ?? - new ShardingWrapOptionsExtension(shardingRuntimeContext); + new ShardingWrapOptionsExtension(); + private static ShardingOptionsExtension CreateOrGetShardingOptionsExtension(this DbContextOptionsBuilder optionsBuilder,IShardingRuntimeContext shardingRuntimeContext) + => optionsBuilder.Options.FindExtension() ?? + new ShardingOptionsExtension(shardingRuntimeContext); public static DbContextOptionsBuilder UseInnerDbContextSharding(this DbContextOptionsBuilder optionsBuilder) { diff --git a/src/ShardingCore/ShardingRuntimeBuilder.cs b/src/ShardingCore/ShardingRuntimeBuilder.cs index f6b1780e..4e297607 100644 --- a/src/ShardingCore/ShardingRuntimeBuilder.cs +++ b/src/ShardingCore/ShardingRuntimeBuilder.cs @@ -67,7 +67,7 @@ namespace ShardingCore shardingRuntimeContext.UseLogfactory(loggerFactory); shardingRuntimeContext.AddServiceConfig(services => { - services.AddSingleton(sp => new DbContextTypeCollector()); + // services.AddSingleton(sp => new DbContextTypeCollector()); services.AddSingleton(sp => _shardingRouteConfigOptions); services.AddSingleton(sp => _shardingConfigOptions); diff --git a/src/ShardingCore/VirtualRoutes/Abstractions/AbstractShardingAutoCreateOperatorVirtualTableRoute.cs b/src/ShardingCore/VirtualRoutes/Abstractions/AbstractShardingAutoCreateOperatorVirtualTableRoute.cs index 9ee640bc..e418790e 100644 --- a/src/ShardingCore/VirtualRoutes/Abstractions/AbstractShardingAutoCreateOperatorVirtualTableRoute.cs +++ b/src/ShardingCore/VirtualRoutes/Abstractions/AbstractShardingAutoCreateOperatorVirtualTableRoute.cs @@ -26,7 +26,7 @@ namespace ShardingCore.VirtualRoutes.Abstractions /// 不可以设置一样 /// public virtual string JobName => - $"{EntityMetadata?.ShardingDbContextType?.Name}:{EntityMetadata?.EntityType?.Name}"; + $"{GetType().Name}:{EntityMetadata?.EntityType?.Name}"; /// /// 是否需要自动创建按时间分表的路由 diff --git a/test/ShardingCore.CommonTest/ShardingDataSourceMod.cs b/test/ShardingCore.CommonTest/ShardingDataSourceMod.cs index 7c6cd19b..f52b8b2b 100644 --- a/test/ShardingCore.CommonTest/ShardingDataSourceMod.cs +++ b/test/ShardingCore.CommonTest/ShardingDataSourceMod.cs @@ -14,8 +14,7 @@ namespace ShardingCore.CommonTest private readonly List _allDataSources; public ShardingDataSourceMod() { - var entityMetadata = new EntityMetadata(typeof(TestEntity), nameof(TestEntity), typeof(ShardingDataSourceMod), - new ReadOnlyCollection(typeof(TestEntity).GetProperties().ToList()), null); + var entityMetadata = new EntityMetadata(typeof(TestEntity)); var entityMetadataDataSourceBuilder = EntityMetadataDataSourceBuilder.CreateEntityMetadataDataSourceBuilder(entityMetadata); entityMetadataDataSourceBuilder.ShardingProperty(o => o.Id); entityMetadata.CheckShardingDataSourceMetadata(); diff --git a/test/ShardingCore.CommonTest/ShardingTableTime.cs b/test/ShardingCore.CommonTest/ShardingTableTime.cs index d67b98bb..39fcda22 100644 --- a/test/ShardingCore.CommonTest/ShardingTableTime.cs +++ b/test/ShardingCore.CommonTest/ShardingTableTime.cs @@ -15,8 +15,7 @@ namespace ShardingCore.CommonTest private readonly List _allTables; public ShardingTableTime() { - var entityMetadata = new EntityMetadata(typeof(TestTimeEntity), nameof(TestTimeEntity), typeof(ShardingDataSourceMod), - new ReadOnlyCollection(typeof(TestTimeEntity).GetProperties().ToList()), null); + var entityMetadata = new EntityMetadata(typeof(TestTimeEntity)); var entityMetadataTableBuilder = EntityMetadataTableBuilder.CreateEntityMetadataTableBuilder(entityMetadata); entityMetadataTableBuilder.ShardingProperty(o => o.Time); entityMetadata.CheckShardingTableMetadata();