From 8729d346a2aa627b47b0529a71536c52cd333e96 Mon Sep 17 00:00:00 2001 From: xuejiaming <326308290@qq.com> Date: Wed, 20 Jul 2022 13:44:52 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A4=9AIShardingRuntimeCont?= =?UTF-8?q?ext=E5=8F=AA=E5=AF=B9=E5=BA=94=E4=B8=80=E4=B8=AAServiceProvider?= =?UTF-8?q?=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Controllers/WeatherForecastController.cs | 2 + samples/Sample.MySql/DIExtension.cs | 11 ++ samples/Sample.MySql/Sample.MySql.csproj | 2 +- samples/Sample.MySql/Startup.cs | 143 +++++++++++++----- samples/Sample.MySql/multi/MyUser.cs | 8 + samples/Sample.MySql/multi/MyUserRoute.cs | 16 ++ samples/Sample.MySql/multi/OtherDbContext.cs | 16 ++ .../IShardingRuntimeContextManager.cs | 17 +++ .../ShardingRuntimeContextManager.cs | 32 ++++ .../ShardingOptionsExtension.cs | 44 +++--- .../EFCores/ShardingInternalDbSet.cs | 4 +- .../EFCores/ShardingModelCacheKeyFactory.cs | 5 +- .../EFCores/ShardingModelCustomizer.cs | 6 +- .../EFCores/ShardingQueryCompiler.cs | 1 + .../Extensions/DbContextExtension.cs | 16 +- .../Extensions/ShardingDbContextExtension.cs | 6 - .../Extensions/ShardingExtension.cs | 8 +- .../ShardingPageExtension.cs | 4 +- .../Extensions/ShardingReadWriteExtension.cs | 4 +- .../AsyncTrackerEnumerator.cs | 4 +- .../TrackerEnumerators/TrackerEnumerator.cs | 2 +- .../Enumerators/DefaultEnumeratorExecutor.cs | 1 + .../Visitors/ShardingQueryPrepareVisitor.cs | 2 +- .../DataSourceDbContext.cs | 2 +- .../ShardingDbContextExecutor.cs | 2 +- .../DefaultShardingQueryExecutor.cs | 2 - .../MergeQueryCompilerContext.cs | 2 +- .../ShardingExecutors/QueryCompilerContext.cs | 2 +- .../Sharding/StreamMergeContext.cs | 4 +- .../Visitors/ShardingExpressionVisitor.cs | 80 +++++----- src/ShardingCore/ShardingCore.csproj | 4 +- src/ShardingCore/ShardingCoreExtension.cs | 50 +++++- src3x/ShardingCore.3x/ShardingCore.3x.csproj | 4 +- 33 files changed, 369 insertions(+), 137 deletions(-) create mode 100644 samples/Sample.MySql/multi/MyUser.cs create mode 100644 samples/Sample.MySql/multi/MyUserRoute.cs create mode 100644 samples/Sample.MySql/multi/OtherDbContext.cs create mode 100644 src/ShardingCore/Core/RuntimeContexts/IShardingRuntimeContextManager.cs create mode 100644 src/ShardingCore/Core/RuntimeContexts/ShardingRuntimeContextManager.cs diff --git a/samples/Sample.MySql/Controllers/WeatherForecastController.cs b/samples/Sample.MySql/Controllers/WeatherForecastController.cs index d22dafeb..e906d9d8 100644 --- a/samples/Sample.MySql/Controllers/WeatherForecastController.cs +++ b/samples/Sample.MySql/Controllers/WeatherForecastController.cs @@ -35,7 +35,9 @@ namespace Sample.MySql.Controllers var resultX = await _defaultTableDbContext.Set() .Where(o => o.Id == "2" || o.Id == "3").FirstOrDefaultAsync(); var resultY = await _defaultTableDbContext.Set().FirstOrDefaultAsync(o => o.Id == "2" || o.Id == "3"); + var shardingFirstOrDefaultAsyncxxx = await _defaultTableDbContext.Set().Where(o=>o.Time==DateTime.Now).ToListAsync(); var result = await _defaultTableDbContext.Set().AnyAsync(); + var result22 = await _defaultTableDbContext.Set().Where(o => o.Id == "2"&&o.Name=="ds1").ToListAsync(); 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(); diff --git a/samples/Sample.MySql/DIExtension.cs b/samples/Sample.MySql/DIExtension.cs index c88dc3a4..177d93a8 100644 --- a/samples/Sample.MySql/DIExtension.cs +++ b/samples/Sample.MySql/DIExtension.cs @@ -5,6 +5,8 @@ using Sample.MySql.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; +using Microsoft.EntityFrameworkCore.Internal; +using Sample.MySql.multi; using ShardingCore.Bootstrappers; namespace Sample.MySql @@ -21,6 +23,8 @@ namespace Sample.MySql { using (var scope=app.ApplicationServices.CreateScope()) { + var otherDbContext =scope.ServiceProvider.GetService(); + var any = otherDbContext.MyUsers.Any(); var virtualDbContext =scope.ServiceProvider.GetService(); if (!virtualDbContext.Set().Any()) { @@ -51,6 +55,13 @@ namespace Sample.MySql } } + + // using (var scope=app.ApplicationServices.CreateScope()) + // { + // + // var virtualDbContext =scope.ServiceProvider.GetService(); + // var any = virtualDbContext.Set().Any(); + // } //using (var scope = app.ApplicationServices.CreateScope()) //{ // var dbContext = scope.ServiceProvider.GetService(); diff --git a/samples/Sample.MySql/Sample.MySql.csproj b/samples/Sample.MySql/Sample.MySql.csproj index 7d57ddf0..547b0940 100644 --- a/samples/Sample.MySql/Sample.MySql.csproj +++ b/samples/Sample.MySql/Sample.MySql.csproj @@ -7,7 +7,7 @@ - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/samples/Sample.MySql/Startup.cs b/samples/Sample.MySql/Startup.cs index ce8db128..a52b1f98 100644 --- a/samples/Sample.MySql/Startup.cs +++ b/samples/Sample.MySql/Startup.cs @@ -3,6 +3,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Migrations; using Sample.MySql.DbContexts; using Sample.MySql.Domain.Entities; +using Sample.MySql.multi; using Sample.MySql.Shardings; using ShardingCore; using ShardingCore.Bootstrappers; @@ -11,6 +12,7 @@ using ShardingCore.Core.RuntimeContexts; using ShardingCore.EFCores; using ShardingCore.Extensions; using ShardingCore.Helpers; +using ShardingCore.Sharding.ReadWriteConfigurations; using ShardingCore.TableExists; using ShardingCore.TableExists.Abstractions; @@ -37,8 +39,10 @@ namespace Sample.MySql { public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder => { - builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole(); + builder.AddFilter((category, level) => + category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole(); }); + public Startup(IConfiguration configuration) { Configuration = configuration; @@ -61,52 +65,90 @@ namespace Sample.MySql // op.AddShardingTableRoute(); // op.AddShardingTableRoute(); // }); - + services.AddMultiShardingDbContext() + .UseRouteConfig(op => { op.AddShardingTableRoute(); }) + .UseConfig(o => + { + o.ThrowIfQueryRouteNotMatch = false; + o.UseShardingQuery((conStr, builder) => + { + builder.UseMySql(conStr, new MySqlServerVersion(new Version())) + .UseLoggerFactory(efLogger) + .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); + }); + o.UseShardingTransaction((connection, builder) => + { + builder + .UseMySql(connection, new MySqlServerVersion(new Version())) + .UseLoggerFactory(efLogger) + .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); + }); + o.UseShardingMigrationConfigure(b => + { + b.ReplaceService(); + }); + o.AddDefaultDataSource("ds0", + "server=127.0.0.1;port=3306;database=dbdbdx;userid=root;password=root;"); + }).AddShardingCore(); services.AddSingleton(sp => { - Stopwatch stopwatch=Stopwatch.StartNew(); - + Stopwatch stopwatch = Stopwatch.StartNew(); + var shardingRuntimeContext = new ShardingRuntimeBuilder() .UseRouteConfig(o => { o.AddShardingTableRoute(); o.AddShardingTableRoute(); - o.AddShardingDataSourceRoute(); + o.AddShardingDataSourceRoute(); }).UseConfig(o => { o.ThrowIfQueryRouteNotMatch = false; - o.UseShardingQuery((conStr,builder)=> + o.UseShardingQuery((conStr, builder) => { builder.UseMySql(conStr, new MySqlServerVersion(new Version())) - .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) .UseLoggerFactory(efLogger) - .EnableSensitiveDataLogging(); + .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); o.UseShardingTransaction((connection, builder) => { builder - .UseMySql(connection, new MySqlServerVersion(new Version())). - UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking) + .UseMySql(connection, new MySqlServerVersion(new Version())) .UseLoggerFactory(efLogger) - .EnableSensitiveDataLogging(); + .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); - o.AddDefaultDataSource("ds0", "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); - o.AddExtraDataSource(sp=>new Dictionary() + o.AddDefaultDataSource("ds0", + "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); + o.AddExtraDataSource(sp => new Dictionary() { - {"ds1", "server=127.0.0.1;port=3306;database=dbdbd1;userid=root;password=root;"}, - {"ds2", "server=127.0.0.1;port=3306;database=dbdbd2;userid=root;password=root;"} + { "ds1", "server=127.0.0.1;port=3306;database=dbdbd1;userid=root;password=root;" }, + { "ds2", "server=127.0.0.1;port=3306;database=dbdbd2;userid=root;password=root;" } }); + o.AddReadWriteSeparation(sp => + { + return new Dictionary>() + { + { + "ds0", + new[] + { + "server=127.0.0.1;port=3306;database=dbdbd0_0;userid=root;password=root;" + } + } + }; + }, defaultEnable: true, readStrategyEnum: ReadStrategyEnum.Loop, + readConnStringGetStrategy: ReadConnStringGetStrategyEnum.LatestEveryTime); o.UseShardingMigrationConfigure(b => { b.ReplaceService(); }); - }).ReplaceService(ServiceLifetime.Singleton) + })//.ReplaceService(ServiceLifetime.Singleton) .Build(sp); stopwatch.Stop(); - Console.WriteLine("ShardingRuntimeContext build:"+stopwatch.ElapsedMilliseconds); + Console.WriteLine("ShardingRuntimeContext build:" + stopwatch.ElapsedMilliseconds); return shardingRuntimeContext; }); - services.AddDbContext(ShardingCoreExtension.UseDefaultSharding); + services.AddDbContext(ShardingCoreExtension + .UseMutliDefaultSharding); // services.AddShardingDbContext() // .AddEntityConfig(o => // { @@ -151,29 +193,56 @@ namespace Sample.MySql { app.UseDeveloperExceptionPage(); } - app.ApplicationServices.UseAutoShardingCreate(); - var shardingRuntimeContext = app.ApplicationServices.GetRequiredService(); - var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); - var entityMetadata = entityMetadataManager.TryGet(); - using (var scope = app.ApplicationServices.CreateScope()) - { - var defaultShardingDbContext = scope.ServiceProvider.GetService(); - // if (defaultShardingDbContext.Database.GetPendingMigrations().Any()) - { - defaultShardingDbContext.Database.Migrate(); - } - } - app.ApplicationServices.UseAutoTryCompensateTable(12); - + var shardingRuntimeContextManager = app.ApplicationServices.GetRequiredService(); + var shardingRuntimeContexts = shardingRuntimeContextManager.GetAll(); + foreach (var keyValuePair in shardingRuntimeContexts) + { + keyValuePair.Value.UseAutoShardingCreate(); + keyValuePair.Value.UseAutoTryCompensateTable(); + } + // app.ApplicationServices.UseAutoShardingCreate(); + // var shardingRuntimeContext = app.ApplicationServices.GetRequiredService(); + // var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); + // var entityMetadata = entityMetadataManager.TryGet(); + // using (var scope = app.ApplicationServices.CreateScope()) + // { + // var defaultShardingDbContext = scope.ServiceProvider.GetService(); + // // if (defaultShardingDbContext.Database.GetPendingMigrations().Any()) + // { + // try + // { + // + // defaultShardingDbContext.Database.Migrate(); + // } + // catch (Exception e) + // { + // } + // } + // } + // using (var scope = app.ApplicationServices.CreateScope()) + // { + // var defaultShardingDbContext = scope.ServiceProvider.GetService(); + // // if (defaultShardingDbContext.Database.GetPendingMigrations().Any()) + // { + // try + // { + // + // defaultShardingDbContext.Database.Migrate(); + // } + // catch (Exception e) + // { + // } + // } + // } + // + // app.ApplicationServices.UseAutoTryCompensateTable(12); + app.UseRouting(); app.UseAuthorization(); - app.UseEndpoints(endpoints => - { - endpoints.MapControllers(); - }); + app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); // for (int i = 1; i < 500; i++) // { // using (var conn = new MySqlConnection( @@ -187,4 +256,4 @@ namespace Sample.MySql app.DbSeed(); } } -} +} \ No newline at end of file diff --git a/samples/Sample.MySql/multi/MyUser.cs b/samples/Sample.MySql/multi/MyUser.cs new file mode 100644 index 00000000..945a82b3 --- /dev/null +++ b/samples/Sample.MySql/multi/MyUser.cs @@ -0,0 +1,8 @@ +using System.ComponentModel.DataAnnotations.Schema; + +namespace Sample.MySql.multi; +[Table("MyUser")] +public class MyUser +{ + public string Id { get; set; } +} \ No newline at end of file diff --git a/samples/Sample.MySql/multi/MyUserRoute.cs b/samples/Sample.MySql/multi/MyUserRoute.cs new file mode 100644 index 00000000..cb71a695 --- /dev/null +++ b/samples/Sample.MySql/multi/MyUserRoute.cs @@ -0,0 +1,16 @@ +using ShardingCore.Core.EntityMetadatas; +using ShardingCore.VirtualRoutes.Mods; + +namespace Sample.MySql.multi; + +public class MyUserRoute:AbstractSimpleShardingModKeyStringVirtualTableRoute +{ + public MyUserRoute() : base(1, 3) + { + } + + public override void Configure(EntityMetadataTableBuilder builder) + { + builder.ShardingProperty(o => o.Id); + } +} \ No newline at end of file diff --git a/samples/Sample.MySql/multi/OtherDbContext.cs b/samples/Sample.MySql/multi/OtherDbContext.cs new file mode 100644 index 00000000..4c8bb076 --- /dev/null +++ b/samples/Sample.MySql/multi/OtherDbContext.cs @@ -0,0 +1,16 @@ +using Microsoft.EntityFrameworkCore; +using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions; +using ShardingCore.Sharding; +using ShardingCore.Sharding.Abstractions; + +namespace Sample.MySql.multi; + +public class OtherDbContext:AbstractShardingDbContext,IShardingTableDbContext +{ + public DbSet MyUsers { get; set; } + public OtherDbContext(DbContextOptions options) : base(options) + { + } + + public IRouteTail RouteTail { get; set; } +} \ No newline at end of file diff --git a/src/ShardingCore/Core/RuntimeContexts/IShardingRuntimeContextManager.cs b/src/ShardingCore/Core/RuntimeContexts/IShardingRuntimeContextManager.cs new file mode 100644 index 00000000..48c65a19 --- /dev/null +++ b/src/ShardingCore/Core/RuntimeContexts/IShardingRuntimeContextManager.cs @@ -0,0 +1,17 @@ +using System; +using System.Collections.Generic; + +namespace ShardingCore.Core.RuntimeContexts +{ + public interface IShardingRuntimeContextManager + { + /// + /// 尝试获取注册的dbcontext type对应的 没有返回null + /// + /// + /// + IShardingRuntimeContext TryGet(Type dbContextType); + + IReadOnlyDictionary GetAll(); + } +} \ No newline at end of file diff --git a/src/ShardingCore/Core/RuntimeContexts/ShardingRuntimeContextManager.cs b/src/ShardingCore/Core/RuntimeContexts/ShardingRuntimeContextManager.cs new file mode 100644 index 00000000..585aed6e --- /dev/null +++ b/src/ShardingCore/Core/RuntimeContexts/ShardingRuntimeContextManager.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; + +namespace ShardingCore.Core.RuntimeContexts +{ + + public class ShardingRuntimeContextManager:IShardingRuntimeContextManager + { + private readonly ImmutableDictionary _caches; + public ShardingRuntimeContextManager(IEnumerable shardingRuntimeContexts) + { + _caches = shardingRuntimeContexts.ToImmutableDictionary(o => o.DbContextType, o => o); + } + public IShardingRuntimeContext TryGet(Type dbContextType) + { + if (_caches.TryGetValue(dbContextType, out var shardingRuntimeContext)) + { + return shardingRuntimeContext; + } + + return null; + } + + public IReadOnlyDictionary GetAll() + { + return _caches; + } + } +} diff --git a/src/ShardingCore/EFCores/OptionsExtensions/ShardingOptionsExtension.cs b/src/ShardingCore/EFCores/OptionsExtensions/ShardingOptionsExtension.cs index 501f65f9..1776768f 100644 --- a/src/ShardingCore/EFCores/OptionsExtensions/ShardingOptionsExtension.cs +++ b/src/ShardingCore/EFCores/OptionsExtensions/ShardingOptionsExtension.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.Extensions.DependencyInjection; @@ -19,15 +20,15 @@ namespace ShardingCore.EFCores.OptionsExtensions #if EFCORE6 public class ShardingOptionsExtension : IDbContextOptionsExtension { - private readonly IShardingRuntimeContext _shardingRuntimeContext; + public IShardingRuntimeContext ShardingRuntimeContext { get; } public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext) { - _shardingRuntimeContext = shardingRuntimeContext; + ShardingRuntimeContext = shardingRuntimeContext; } public void ApplyServices(IServiceCollection services) { - services.AddSingleton(sp => _shardingRuntimeContext); + services.AddSingleton(sp =>ShardingRuntimeContext); } public void Validate(IDbContextOptions options) @@ -35,15 +36,17 @@ namespace ShardingCore.EFCores.OptionsExtensions } - public DbContextOptionsExtensionInfo Info => new ShardingWrapDbContextOptionsExtensionInfo(this); + public DbContextOptionsExtensionInfo Info => new ShardingOptionsExtensionInfo(this); - private class ShardingWrapDbContextOptionsExtensionInfo : DbContextOptionsExtensionInfo + private class ShardingOptionsExtensionInfo : DbContextOptionsExtensionInfo { - public ShardingWrapDbContextOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + private readonly ShardingOptionsExtension _shardingOptionsExtension; + public ShardingOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) { + _shardingOptionsExtension = (ShardingOptionsExtension)extension; } - public override int GetServiceProviderHashCode() => 0; + public override int GetServiceProviderHashCode() => _shardingOptionsExtension.ShardingRuntimeContext.GetHashCode(); public override bool ShouldUseSameServiceProvider(DbContextOptionsExtensionInfo other) => true; @@ -60,15 +63,15 @@ namespace ShardingCore.EFCores.OptionsExtensions public class ShardingOptionsExtension: IDbContextOptionsExtension { - private readonly IShardingRuntimeContext _shardingRuntimeContext; + public IShardingRuntimeContext ShardingRuntimeContext { get; } public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext) { - _shardingRuntimeContext = shardingRuntimeContext; + ShardingRuntimeContext = shardingRuntimeContext; } public void ApplyServices(IServiceCollection services) { - services.AddSingleton(sp => _shardingRuntimeContext); + services.AddSingleton(sp => ShardingRuntimeContext); } public void Validate(IDbContextOptions options) @@ -76,13 +79,18 @@ namespace ShardingCore.EFCores.OptionsExtensions } - public DbContextOptionsExtensionInfo Info => new ShardingWrapDbContextOptionsExtensionInfo(this); + public DbContextOptionsExtensionInfo Info => new ShardingOptionsExtensionInfo(this); - private class ShardingWrapDbContextOptionsExtensionInfo : DbContextOptionsExtensionInfo + private class ShardingOptionsExtensionInfo : DbContextOptionsExtensionInfo { - public ShardingWrapDbContextOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) { } + private readonly ShardingOptionsExtension _shardingOptionsExtension; + public ShardingOptionsExtensionInfo(IDbContextOptionsExtension extension) : base(extension) + { + _shardingOptionsExtension = (ShardingOptionsExtension)extension; + } - public override long GetServiceProviderHashCode() => 0; + + public override long GetServiceProviderHashCode() => _shardingOptionsExtension.ShardingRuntimeContext.GetHashCode(); public override void PopulateDebugInfo(IDictionary debugInfo) { } @@ -96,18 +104,18 @@ namespace ShardingCore.EFCores.OptionsExtensions public class ShardingOptionsExtension: IDbContextOptionsExtension { - private readonly IShardingRuntimeContext _shardingRuntimeContext; + public IShardingRuntimeContext ShardingRuntimeContext { get; } public ShardingOptionsExtension(IShardingRuntimeContext shardingRuntimeContext) { - _shardingRuntimeContext = shardingRuntimeContext; + ShardingRuntimeContext = shardingRuntimeContext; } public bool ApplyServices(IServiceCollection services) { - services.AddSingleton(sp => _shardingRuntimeContext); + services.AddSingleton(sp => ShardingRuntimeContext); return true; } - public long GetServiceProviderHashCode() => 0; + public long GetServiceProviderHashCode() => ShardingRuntimeContext.GetHashCode(); public void Validate(IDbContextOptions options) { diff --git a/src/ShardingCore/EFCores/ShardingInternalDbSet.cs b/src/ShardingCore/EFCores/ShardingInternalDbSet.cs index 74593de7..55351581 100644 --- a/src/ShardingCore/EFCores/ShardingInternalDbSet.cs +++ b/src/ShardingCore/EFCores/ShardingInternalDbSet.cs @@ -37,14 +37,14 @@ namespace ShardingCore.EFCores public ShardingInternalDbSet(DbContext context, string entityTypeName) : base(context, entityTypeName) { _context = (IShardingDbContext)context; - _shardingRuntimeContext = context.GetService(); + _shardingRuntimeContext = context.GetShardingRuntimeContext(); } #endif #if EFCORE2 || EFCORE3 public ShardingInternalDbSet(DbContext context) : base(context) { _context = (IShardingDbContext)context; - _shardingRuntimeContext = context.GetService(); + _shardingRuntimeContext = context.GetShardingRuntimeContext(); } #endif diff --git a/src/ShardingCore/EFCores/ShardingModelCacheKeyFactory.cs b/src/ShardingCore/EFCores/ShardingModelCacheKeyFactory.cs index 2eb3412e..c7144dd8 100644 --- a/src/ShardingCore/EFCores/ShardingModelCacheKeyFactory.cs +++ b/src/ShardingCore/EFCores/ShardingModelCacheKeyFactory.cs @@ -16,7 +16,10 @@ namespace ShardingCore.EFCores public class ShardingModelCacheKeyFactory : IModelCacheKeyFactory { - + public ShardingModelCacheKeyFactory() + { + Console.WriteLine("ShardingModelCacheKeyFactory"); + } public object Create(DbContext context) { return Create(context, false); diff --git a/src/ShardingCore/EFCores/ShardingModelCustomizer.cs b/src/ShardingCore/EFCores/ShardingModelCustomizer.cs index c09b75b5..b4245a93 100644 --- a/src/ShardingCore/EFCores/ShardingModelCustomizer.cs +++ b/src/ShardingCore/EFCores/ShardingModelCustomizer.cs @@ -1,9 +1,11 @@ using System; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Text; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Internal; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -11,6 +13,7 @@ using ShardingCore.Core; using ShardingCore.Core.EntityMetadatas; using ShardingCore.Core.RuntimeContexts; using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions; +using ShardingCore.Extensions; using ShardingCore.Extensions.InternalExtensions; using ShardingCore.Sharding.Abstractions; @@ -38,8 +41,7 @@ namespace ShardingCore.EFCores if (context is IShardingTableDbContext shardingTableDbContext&& shardingTableDbContext.RouteTail !=null&& shardingTableDbContext.RouteTail.IsShardingTableQuery()) { - - var shardingRuntimeContext = context.GetService(); + var shardingRuntimeContext = context.GetShardingRuntimeContext(); var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); var isMultiEntityQuery = shardingTableDbContext.RouteTail.IsMultiEntityQuery(); if (!isMultiEntityQuery) diff --git a/src/ShardingCore/EFCores/ShardingQueryCompiler.cs b/src/ShardingCore/EFCores/ShardingQueryCompiler.cs index abfacb80..7d13497f 100644 --- a/src/ShardingCore/EFCores/ShardingQueryCompiler.cs +++ b/src/ShardingCore/EFCores/ShardingQueryCompiler.cs @@ -29,6 +29,7 @@ namespace ShardingCore.EFCores { _shardingDbContext = currentContext.Context as IShardingDbContext ?? throw new ShardingCoreException("db context operator is not IShardingDbContext"); + Console.WriteLine("ShardingQueryCompiler"+shardingRuntimeContext.DbContextType); _shardingCompilerExecutor = shardingRuntimeContext.GetShardingCompilerExecutor(); } diff --git a/src/ShardingCore/Extensions/DbContextExtension.cs b/src/ShardingCore/Extensions/DbContextExtension.cs index e1e986d2..c964d751 100644 --- a/src/ShardingCore/Extensions/DbContextExtension.cs +++ b/src/ShardingCore/Extensions/DbContextExtension.cs @@ -17,6 +17,7 @@ using ShardingCore.Core; using ShardingCore.Core.EntityMetadatas; using ShardingCore.Core.RuntimeContexts; using ShardingCore.EFCores; +using ShardingCore.EFCores.OptionsExtensions; using ShardingCore.Exceptions; using ShardingCore.Utils; @@ -42,7 +43,7 @@ namespace ShardingCore.Extensions var contextModel = dbContext.Model as Model; #endif - var shardingRuntimeContext = dbContext.GetRequireService(); + var shardingRuntimeContext = dbContext.GetShardingRuntimeContext(); var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); #if EFCORE6 @@ -119,7 +120,7 @@ namespace ShardingCore.Extensions var contextModel = dbContext.Model as Model; #endif - var shardingRuntimeContext = dbContext.GetRequireService(); + var shardingRuntimeContext = dbContext.GetShardingRuntimeContext(); var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); #if EFCORE6 @@ -327,15 +328,16 @@ namespace ShardingCore.Extensions //return entry?.Entity; } - public static TService GetRequireService(this DbContext dbContext) where TService:class + public static IShardingRuntimeContext GetShardingRuntimeContext(this DbContext dbContext) { - var service = dbContext.GetService(); - if (service == null) + var shardingRuntimeContext = dbContext.GetService(); + + if (shardingRuntimeContext == null) { - throw new ShardingCoreInvalidOperationException($"cant resolve:[{typeof(TService)}]"); + throw new ShardingCoreInvalidOperationException($"cant resolve:[{typeof(IShardingRuntimeContext)}],dbcontext:[{dbContext}]"); } - return service; + return shardingRuntimeContext; } } diff --git a/src/ShardingCore/Extensions/ShardingDbContextExtension.cs b/src/ShardingCore/Extensions/ShardingDbContextExtension.cs index ffb01df8..19e9bb67 100644 --- a/src/ShardingCore/Extensions/ShardingDbContextExtension.cs +++ b/src/ShardingCore/Extensions/ShardingDbContextExtension.cs @@ -30,12 +30,6 @@ namespace ShardingCore.Extensions return dbContext.GetService().ContextOptions.FindExtension() is not null; } - public static IShardingRuntimeContext GetShardingRuntimeContext(this IShardingDbContext shardingDbContext) - { - return ((DbContext)shardingDbContext).GetRequireService(); - } - - /// /// 创建共享链接DbConnection /// diff --git a/src/ShardingCore/Extensions/ShardingExtension.cs b/src/ShardingCore/Extensions/ShardingExtension.cs index 79e3ea6b..1462f46d 100644 --- a/src/ShardingCore/Extensions/ShardingExtension.cs +++ b/src/ShardingCore/Extensions/ShardingExtension.cs @@ -89,7 +89,7 @@ namespace ShardingCore.Extensions { if (entities.IsEmpty()) return new Dictionary>>(); - var shardingRuntimeContext = shardingDbContext.GetRequireService(); + var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); var entityType = typeof(TEntity); var routeTailFactory = shardingRuntimeContext.GetRouteTailFactory(); var virtualDataSource = shardingDbContext.GetVirtualDataSource(); @@ -225,7 +225,7 @@ namespace ShardingCore.Extensions IEnumerable entities) where TShardingDbContext : DbContext, IShardingDbContext where TEntity : class { - var shardingRuntimeContext = shardingDbContext.GetRequireService(); + var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager(); if (entityMetadataManager.IsShardingDataSource(typeof(TEntity))) throw new ShardingCoreInvalidOperationException(typeof(TEntity).FullName); @@ -246,7 +246,7 @@ namespace ShardingCore.Extensions public static IDictionary> BulkShardingExpression(this TShardingDbContext shardingDbContext, Expression> where) where TEntity : class where TShardingDbContext : DbContext, IShardingDbContext { - var shardingRuntimeContext = shardingDbContext.GetRequireService(); + var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); var routeTailFactory = shardingRuntimeContext.GetRouteTailFactory(); var dataSourceRouteManager = shardingRuntimeContext.GetDataSourceRouteManager(); var tableRouteManager = shardingRuntimeContext.GetTableRouteManager();// (IVirtualTableManager)ShardingContainer.GetService(typeof(IVirtualTableManager<>).GetGenericType0(shardingDbContext.GetType())); @@ -289,7 +289,7 @@ namespace ShardingCore.Extensions public static IEnumerable BulkShardingTableExpression(this TShardingDbContext shardingDbContext, Expression> where) where TEntity : class where TShardingDbContext : DbContext, IShardingDbContext { - var shardingRuntimeContext = shardingDbContext.GetRequireService(); + var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();// (IEntityMetadataManager)ShardingContainer.GetService(typeof(IEntityMetadataManager<>).GetGenericType0(shardingDbContext.GetType())); if (entityMetadataManager.IsShardingDataSource(typeof(TEntity))) throw new ShardingCoreInvalidOperationException(typeof(TEntity).FullName); diff --git a/src/ShardingCore/Extensions/ShardingPageExtensions/ShardingPageExtension.cs b/src/ShardingCore/Extensions/ShardingPageExtensions/ShardingPageExtension.cs index 8d68fdac..3c479876 100644 --- a/src/ShardingCore/Extensions/ShardingPageExtensions/ShardingPageExtension.cs +++ b/src/ShardingCore/Extensions/ShardingPageExtensions/ShardingPageExtension.cs @@ -44,7 +44,7 @@ namespace ShardingCore.Extensions.ShardingPageExtensions public static async Task> ToShardingPageAsync(this IQueryable source, int pageIndex, int pageSize) { var shardingDbContext = GetShardingDbContext(source); - var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); + var shardingRuntimeContext = ((DbContext)shardingDbContext).GetShardingRuntimeContext(); //设置每次获取多少页 var take = pageSize <= 0 ? 1 : pageSize; @@ -79,7 +79,7 @@ namespace ShardingCore.Extensions.ShardingPageExtensions public static ShardingPagedResult ToShardingPage(this IQueryable source, int pageIndex, int pageSize) { var shardingDbContext = GetShardingDbContext(source); - var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); + var shardingRuntimeContext = ((DbContext)shardingDbContext).GetShardingRuntimeContext(); //设置每次获取多少页 var take = pageSize <= 0 ? 1 : pageSize; //设置当前页码最小1 diff --git a/src/ShardingCore/Extensions/ShardingReadWriteExtension.cs b/src/ShardingCore/Extensions/ShardingReadWriteExtension.cs index b890de6d..88144fba 100644 --- a/src/ShardingCore/Extensions/ShardingReadWriteExtension.cs +++ b/src/ShardingCore/Extensions/ShardingReadWriteExtension.cs @@ -58,7 +58,7 @@ namespace ShardingCore.Extensions /// 是否是读数据源 private static void SetReadWriteSeparation(this ISupportShardingReadWrite supportShardingReadWrite, bool readOnly) { - var shardingRuntimeContext = ((DbContext)supportShardingReadWrite).GetRequireService(); + var shardingRuntimeContext = ((DbContext)supportShardingReadWrite).GetShardingRuntimeContext(); var shardingReadWriteManager =shardingRuntimeContext.GetService(); var shardingReadWriteContext = shardingReadWriteManager.GetCurrent(); if (shardingReadWriteContext != null) @@ -86,7 +86,7 @@ namespace ShardingCore.Extensions { if (shardingDbContext.IsUseReadWriteSeparation()) { - var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); + var shardingRuntimeContext = ((DbContext)shardingDbContext).GetShardingRuntimeContext(); var shardingReadWriteManager =shardingRuntimeContext.GetService(); var shardingReadWriteContext = shardingReadWriteManager.GetCurrent(); if (shardingReadWriteContext != null) diff --git a/src/ShardingCore/Sharding/Enumerators/TrackerEnumerators/AsyncTrackerEnumerator.cs b/src/ShardingCore/Sharding/Enumerators/TrackerEnumerators/AsyncTrackerEnumerator.cs index e6aaabbf..77f7ca81 100644 --- a/src/ShardingCore/Sharding/Enumerators/TrackerEnumerators/AsyncTrackerEnumerator.cs +++ b/src/ShardingCore/Sharding/Enumerators/TrackerEnumerators/AsyncTrackerEnumerator.cs @@ -27,7 +27,7 @@ namespace ShardingCore.Sharding.Enumerators.TrackerEnumerators public AsyncTrackerEnumerator(IShardingDbContext shardingDbContext, IAsyncEnumerator asyncEnumerator) { - var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); + var shardingRuntimeContext = ((DbContext)shardingDbContext).GetShardingRuntimeContext(); _shardingDbContext = shardingDbContext; _asyncEnumerator = asyncEnumerator; _queryTrack = shardingRuntimeContext.GetQueryTracker(); @@ -70,7 +70,7 @@ namespace ShardingCore.Sharding.Enumerators.TrackerEnumerators public AsyncTrackerEnumerator(IShardingDbContext shardingDbContext, IAsyncEnumerator asyncEnumerator) { - var shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); + var shardingRuntimeContext = ((DbContext)shardingDbContext).GetShardingRuntimeContext(); _shardingDbContext = shardingDbContext; _asyncEnumerator = asyncEnumerator; _queryTrack = shardingRuntimeContext.GetQueryTracker(); diff --git a/src/ShardingCore/Sharding/Enumerators/TrackerEnumerators/TrackerEnumerator.cs b/src/ShardingCore/Sharding/Enumerators/TrackerEnumerators/TrackerEnumerator.cs index d4cd46c9..2e03dd1a 100644 --- a/src/ShardingCore/Sharding/Enumerators/TrackerEnumerators/TrackerEnumerator.cs +++ b/src/ShardingCore/Sharding/Enumerators/TrackerEnumerators/TrackerEnumerator.cs @@ -24,7 +24,7 @@ namespace ShardingCore.Sharding.Enumerators.TrackerEnumerators public TrackerEnumerator(IShardingDbContext shardingDbContext,IEnumerator enumerator) { - var shardingRuntimeContext = ((DbContext)shardingDbContext).GetRequireService(); + var shardingRuntimeContext = ((DbContext)shardingDbContext).GetShardingRuntimeContext(); _shardingDbContext = shardingDbContext; _enumerator = enumerator; _queryTrack = shardingRuntimeContext.GetQueryTracker(); diff --git a/src/ShardingCore/Sharding/MergeEngines/Executors/Enumerators/DefaultEnumeratorExecutor.cs b/src/ShardingCore/Sharding/MergeEngines/Executors/Enumerators/DefaultEnumeratorExecutor.cs index c537c681..2933a130 100644 --- a/src/ShardingCore/Sharding/MergeEngines/Executors/Enumerators/DefaultEnumeratorExecutor.cs +++ b/src/ShardingCore/Sharding/MergeEngines/Executors/Enumerators/DefaultEnumeratorExecutor.cs @@ -5,6 +5,7 @@ using System.Text; using System.Threading; using System.Threading.Tasks; using ShardingCore.Extensions; +using ShardingCore.Sharding.Abstractions; using ShardingCore.Sharding.Enumerators; using ShardingCore.Sharding.Enumerators.StreamMergeAsync; using ShardingCore.Sharding.MergeEngines.Abstractions; diff --git a/src/ShardingCore/Sharding/Parsers/Visitors/ShardingQueryPrepareVisitor.cs b/src/ShardingCore/Sharding/Parsers/Visitors/ShardingQueryPrepareVisitor.cs index b89256a7..de0f40e3 100644 --- a/src/ShardingCore/Sharding/Parsers/Visitors/ShardingQueryPrepareVisitor.cs +++ b/src/ShardingCore/Sharding/Parsers/Visitors/ShardingQueryPrepareVisitor.cs @@ -42,7 +42,7 @@ namespace ShardingCore.Sharding.Parsers.Visitors public ShardingQueryPrepareVisitor(IShardingDbContext shardingDbContext) { _shardingDbContext = shardingDbContext; - _trackerManager =shardingDbContext.GetShardingRuntimeContext() + _trackerManager =((DbContext)shardingDbContext).GetShardingRuntimeContext() .GetTrackerManager(); } public ShardingPrepareResult GetShardingPrepareResult() diff --git a/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs b/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs index 3bfeec60..19757f67 100644 --- a/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs +++ b/src/ShardingCore/Sharding/ShardingDbContextExecutors/DataSourceDbContext.cs @@ -124,7 +124,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors DataSourceName = dataSourceName; IsDefault = isDefault; _shardingShellDbContext = shardingShellDbContext; - _shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); + _shardingRuntimeContext = shardingShellDbContext.GetShardingRuntimeContext(); DbContextType = shardingShellDbContext.GetType(); _virtualDataSource =shardingDbContext .GetVirtualDataSource(); diff --git a/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs b/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs index 7452329b..c3d3d2ab 100644 --- a/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs +++ b/src/ShardingCore/Sharding/ShardingDbContextExecutors/ShardingDbContextExecutor.cs @@ -64,7 +64,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors { _shardingDbContext = shardingDbContext; //初始化 - _shardingRuntimeContext = shardingDbContext.GetRequireService(); + _shardingRuntimeContext = shardingDbContext.GetShardingRuntimeContext(); _shardingRuntimeContext.GetOrCreateShardingRuntimeModel(shardingDbContext); _virtualDataSource = _shardingRuntimeContext.GetVirtualDataSource(); _dataSourceRouteManager = _shardingRuntimeContext.GetDataSourceRouteManager(); diff --git a/src/ShardingCore/Sharding/ShardingExecutors/DefaultShardingQueryExecutor.cs b/src/ShardingCore/Sharding/ShardingExecutors/DefaultShardingQueryExecutor.cs index 2fe77f4f..6476315d 100644 --- a/src/ShardingCore/Sharding/ShardingExecutors/DefaultShardingQueryExecutor.cs +++ b/src/ShardingCore/Sharding/ShardingExecutors/DefaultShardingQueryExecutor.cs @@ -55,13 +55,11 @@ namespace ShardingCore.Sharding.ShardingQueryExecutors if (mergeQueryCompilerContext.IsEnumerableQuery()) { return EnumerableExecute(mergeQueryCompilerContext); - } if (typeof(TResult).HasImplementedRawGeneric(typeof(Task<>))) { return DoExecute(mergeQueryCompilerContext, true, cancellationToken); - } diff --git a/src/ShardingCore/Sharding/ShardingExecutors/MergeQueryCompilerContext.cs b/src/ShardingCore/Sharding/ShardingExecutors/MergeQueryCompilerContext.cs index bafe7b89..132cd8a8 100644 --- a/src/ShardingCore/Sharding/ShardingExecutors/MergeQueryCompilerContext.cs +++ b/src/ShardingCore/Sharding/ShardingExecutors/MergeQueryCompilerContext.cs @@ -101,7 +101,7 @@ namespace ShardingCore.Sharding.ShardingExecutors public static MergeQueryCompilerContext Create(IQueryCompilerContext queryCompilerContext, QueryCombineResult queryCombineResult, ShardingRouteResult shardingRouteResult) { var shardingDbContext = queryCompilerContext.GetShardingDbContext(); - var shardingRuntimeContext = ((DbContext)shardingDbContext).GetRequireService(); + var shardingRuntimeContext = ((DbContext)shardingDbContext).GetShardingRuntimeContext(); return new MergeQueryCompilerContext(shardingRuntimeContext,queryCompilerContext, queryCombineResult,shardingRouteResult); } public Dictionary GetQueryEntities() diff --git a/src/ShardingCore/Sharding/ShardingExecutors/QueryCompilerContext.cs b/src/ShardingCore/Sharding/ShardingExecutors/QueryCompilerContext.cs index a9edbf48..0ca8ba7b 100644 --- a/src/ShardingCore/Sharding/ShardingExecutors/QueryCompilerContext.cs +++ b/src/ShardingCore/Sharding/ShardingExecutors/QueryCompilerContext.cs @@ -39,7 +39,7 @@ namespace ShardingCore.Sharding.ShardingExecutors private QueryCompilerContext(IPrepareParseResult prepareParseResult) { - _shardingRuntimeContext = ((DbContext)prepareParseResult.GetShardingDbContext()).GetRequireService(); + _shardingRuntimeContext = ((DbContext)prepareParseResult.GetShardingDbContext()).GetShardingRuntimeContext(); _shardingDbContext = prepareParseResult.GetShardingDbContext(); _queryExpression = prepareParseResult.GetNativeQueryExpression(); _shardingDbContextType = _shardingDbContext.GetType(); diff --git a/src/ShardingCore/Sharding/StreamMergeContext.cs b/src/ShardingCore/Sharding/StreamMergeContext.cs index 6ce7055c..70fddb4b 100644 --- a/src/ShardingCore/Sharding/StreamMergeContext.cs +++ b/src/ShardingCore/Sharding/StreamMergeContext.cs @@ -93,7 +93,7 @@ namespace ShardingCore.Sharding RewriteQueryable = rewriteResult.GetRewriteQueryable(); OptimizeResult = optimizeResult; _rewriteResult = rewriteResult; - ShardingRuntimeContext = mergeQueryCompilerContext.GetShardingDbContext().GetShardingRuntimeContext(); + ShardingRuntimeContext = ((DbContext)mergeQueryCompilerContext.GetShardingDbContext()).GetShardingRuntimeContext(); _routeTailFactory = ShardingRuntimeContext.GetRouteTailFactory(); _trackerManager = ShardingRuntimeContext.GetTrackerManager(); _shardingConfigOptions = ShardingRuntimeContext.GetShardingConfigOptions(); @@ -289,7 +289,7 @@ namespace ShardingCore.Sharding public IShardingComparer GetShardingComparer() { - return GetShardingDbContext().GetShardingRuntimeContext().GetRequiredService(); + return ((DbContext)GetShardingDbContext()).GetShardingRuntimeContext().GetShardingComparer(); } /// diff --git a/src/ShardingCore/Sharding/Visitors/ShardingExpressionVisitor.cs b/src/ShardingCore/Sharding/Visitors/ShardingExpressionVisitor.cs index 0dc3a821..fcc63ad8 100644 --- a/src/ShardingCore/Sharding/Visitors/ShardingExpressionVisitor.cs +++ b/src/ShardingCore/Sharding/Visitors/ShardingExpressionVisitor.cs @@ -15,9 +15,8 @@ namespace ShardingCore.Core.Internal.Visitors * @Date: Wednesday, 13 January 2021 11:31:01 * @Email: 326308290@qq.com */ - public abstract class ShardingExpressionVisitor:ExpressionVisitor + public abstract class ShardingExpressionVisitor : ExpressionVisitor { - //public object GetFieldValue(Expression expression) //{ // if (expression is ConstantExpression) @@ -50,56 +49,67 @@ namespace ShardingCore.Core.Internal.Visitors return field.GetValue( GetExpressionValue( e.Expression - ) ?? throw new InvalidOperationException($"cant get expression value,{e.Expression.ShardingPrint()} may be null reference") + ) ?? throw new InvalidOperationException( + $"cant get expression value,{e.Expression.ShardingPrint()} may be null reference") ); case MemberExpression e when e.Member is PropertyInfo property: { - if (e.Expression == null&&property.DeclaringType==typeof(DateTime)&&property.Name==nameof(DateTime.Now)) + if (e.Expression == null) { - return DateTime.Now; - } - else - { - return property.GetValue( - GetExpressionValue( - e.Expression - )??throw new InvalidOperationException($"cant get expression value,{e.Expression.ShardingPrint()} may be null reference") - ); + if (property.DeclaringType == typeof(DateTime) && property.Name == nameof(DateTime.Now)) + { + return DateTime.Now; + } + + if (property.DeclaringType == typeof(DateTimeOffset) && + property.Name == nameof(DateTimeOffset.Now)) + { + return DateTimeOffset.Now; + } } + + return property.GetValue( + GetExpressionValue( + e.Expression + ) ?? throw new InvalidOperationException( + $"cant get expression value,{e.Expression.ShardingPrint()} may be null reference") + ); } case ListInitExpression e when e.NewExpression.Arguments.Count() == 0: + { + var collection = e.NewExpression.Constructor.Invoke(new object[0]); + foreach (var i in e.Initializers) { - var collection = e.NewExpression.Constructor.Invoke(new object[0]); - foreach (var i in e.Initializers) - { - i.AddMethod.Invoke( - collection, - i.Arguments - .Select( - a => GetExpressionValue(a) - ) - .ToArray() - ); - } - return collection; + i.AddMethod.Invoke( + collection, + i.Arguments + .Select( + a => GetExpressionValue(a) + ) + .ToArray() + ); } + + return collection; + } case NewArrayExpression e when e.NodeType == ExpressionType.NewArrayInit && e.Expressions.Count > 0: + { + var collection = new List(e.Expressions.Count); + foreach (var arrayItemExpression in e.Expressions) { - var collection = new List(e.Expressions.Count); - foreach (var arrayItemExpression in e.Expressions) - { - collection.Add(GetExpressionValue(arrayItemExpression)); - } - return collection; + collection.Add(GetExpressionValue(arrayItemExpression)); } + return collection; + } + case MethodCallExpression e: { var expressionValue = GetExpressionValue(e.Object); - + return e.Method.Invoke( expressionValue, e.Arguments @@ -116,7 +126,8 @@ namespace ShardingCore.Core.Internal.Visitors default: { - if (expression is BinaryExpression binaryExpression&&expression.NodeType == ExpressionType.ArrayIndex) + if (expression is BinaryExpression binaryExpression && + expression.NodeType == ExpressionType.ArrayIndex) { var index = GetExpressionValue(binaryExpression.Right); if (index is int i) @@ -128,6 +139,7 @@ namespace ShardingCore.Core.Internal.Visitors } } } + //TODO: better messaging throw new ShardingCoreException("cant get value " + expression); } diff --git a/src/ShardingCore/ShardingCore.csproj b/src/ShardingCore/ShardingCore.csproj index e1978835..bf012113 100644 --- a/src/ShardingCore/ShardingCore.csproj +++ b/src/ShardingCore/ShardingCore.csproj @@ -32,8 +32,8 @@ - - + + diff --git a/src/ShardingCore/ShardingCoreExtension.cs b/src/ShardingCore/ShardingCoreExtension.cs index 00420192..54741ad3 100644 --- a/src/ShardingCore/ShardingCoreExtension.cs +++ b/src/ShardingCore/ShardingCoreExtension.cs @@ -91,6 +91,22 @@ namespace ShardingCore return services.AddShardingConfigure(); } + public static ShardingCoreConfigBuilder AddMultiShardingDbContext( + 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(UseMutliDefaultSharding, contextLifetime, + optionsLifetime); + services.TryAddSingleton(); + return services.AddShardingConfigure(); + } + public static ShardingCoreConfigBuilder AddShardingConfigure( this IServiceCollection services) where TShardingDbContext : DbContext, IShardingDbContext @@ -99,18 +115,36 @@ namespace ShardingCore return new ShardingCoreConfigBuilder(services); } - public static void UseDefaultSharding(this DbContextOptionsBuilder dbContextOptionsBuilder,IServiceProvider serviceProvider) where TShardingDbContext : DbContext, IShardingDbContext + public static void UseDefaultSharding(this DbContextOptionsBuilder dbContextOptionsBuilder, + IServiceProvider serviceProvider) where TShardingDbContext : DbContext, IShardingDbContext { var shardingRuntimeContext = serviceProvider.GetRequiredService(); dbContextOptionsBuilder.UseDefaultSharding(shardingRuntimeContext); } + public static void UseDefaultSharding(IServiceProvider serviceProvider, DbContextOptionsBuilder dbContextOptionsBuilder) where TShardingDbContext : DbContext, IShardingDbContext { var shardingRuntimeContext = serviceProvider.GetRequiredService(); dbContextOptionsBuilder.UseDefaultSharding(shardingRuntimeContext); } - public static void UseDefaultSharding(this DbContextOptionsBuilder dbContextOptionsBuilder,IShardingRuntimeContext shardingRuntimeContext) where TShardingDbContext : DbContext, IShardingDbContext + + public static void UseMutliDefaultSharding(IServiceProvider serviceProvider, + DbContextOptionsBuilder dbContextOptionsBuilder) where TShardingDbContext : DbContext, IShardingDbContext + { + var shardingRuntimeContextManager = serviceProvider.GetRequiredService(); + var shardingRuntimeContext = shardingRuntimeContextManager.TryGet(typeof(TShardingDbContext)); + if (shardingRuntimeContext == null) + { + throw new InvalidOperationException( + $"cant get multi sharding runtime context:[{typeof(TShardingDbContext)}]"); + } + + dbContextOptionsBuilder.UseDefaultSharding(shardingRuntimeContext); + } + + public static void UseDefaultSharding(this DbContextOptionsBuilder dbContextOptionsBuilder, + IShardingRuntimeContext shardingRuntimeContext) where TShardingDbContext : DbContext, IShardingDbContext { var shardingConfigOptions = shardingRuntimeContext.GetShardingConfigOptions(); shardingConfigOptions.ShardingMigrationConfigure?.Invoke(dbContextOptionsBuilder); @@ -211,6 +245,7 @@ namespace ShardingCore .ReplaceService>(); } + public static DbContextOptionsBuilder UseShardingMigrator( this DbContextOptionsBuilder optionsBuilder) { @@ -221,6 +256,7 @@ namespace ShardingCore public static DbContextOptionsBuilder UseShardingOptions(this DbContextOptionsBuilder optionsBuilder, IShardingRuntimeContext shardingRuntimeContext) { + var shardingOptionsExtension = optionsBuilder.CreateOrGetShardingOptionsExtension(shardingRuntimeContext); ((IDbContextOptionsBuilderInfrastructure)optionsBuilder).AddOrUpdateExtension(shardingOptionsExtension); return optionsBuilder; @@ -240,9 +276,13 @@ namespace ShardingCore new ShardingWrapOptionsExtension(); private static ShardingOptionsExtension CreateOrGetShardingOptionsExtension( - this DbContextOptionsBuilder optionsBuilder, IShardingRuntimeContext shardingRuntimeContext) - => optionsBuilder.Options.FindExtension() ?? - new ShardingOptionsExtension(shardingRuntimeContext); + this DbContextOptionsBuilder optionsBuilder, IShardingRuntimeContext shardingRuntimeContext) => + optionsBuilder.Options.FindExtension() ?? + new ShardingOptionsExtension(shardingRuntimeContext); + // private static CoreOptionsExtension CreateOrGetCoreOptionsExtension( + // this DbContextOptionsBuilder optionsBuilder) => + // optionsBuilder.Options.FindExtension() ?? + // new CoreOptionsExtension(); public static DbContextOptionsBuilder UseInnerDbContextSharding(this DbContextOptionsBuilder optionsBuilder) { diff --git a/src3x/ShardingCore.3x/ShardingCore.3x.csproj b/src3x/ShardingCore.3x/ShardingCore.3x.csproj index e3c9dd7a..ac35551f 100644 --- a/src3x/ShardingCore.3x/ShardingCore.3x.csproj +++ b/src3x/ShardingCore.3x/ShardingCore.3x.csproj @@ -41,8 +41,8 @@ - - + +