Skip to content

Commit 8729d34

Browse files
committed
修复多IShardingRuntimeContext只对应一个ServiceProvider的bug
1 parent 3fa09c8 commit 8729d34

33 files changed

+367
-135
lines changed

samples/Sample.MySql/Controllers/WeatherForecastController.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,9 @@ public async Task<IActionResult> Get()
3535
var resultX = await _defaultTableDbContext.Set<SysUserMod>()
3636
.Where(o => o.Id == "2" || o.Id == "3").FirstOrDefaultAsync();
3737
var resultY = await _defaultTableDbContext.Set<SysUserMod>().FirstOrDefaultAsync(o => o.Id == "2" || o.Id == "3");
38+
var shardingFirstOrDefaultAsyncxxx = await _defaultTableDbContext.Set<SysUserLogByMonth>().Where(o=>o.Time==DateTime.Now).ToListAsync();
3839
var result = await _defaultTableDbContext.Set<SysTest>().AnyAsync();
40+
var result22 = await _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "2"&&o.Name=="ds1").ToListAsync();
3941
var result1 = await _defaultTableDbContext.Set<SysUserMod>().Where(o => o.Id == "2" || o.Id == "3").ToListAsync();
4042
var result2 = await _defaultTableDbContext.Set<SysUserLogByMonth>().Skip(1).Take(10).ToListAsync();
4143
var shardingFirstOrDefaultAsync = await _defaultTableDbContext.Set<SysUserLogByMonth>().ToListAsync();

samples/Sample.MySql/DIExtension.cs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
using System;
66
using System.Collections.Generic;
77
using System.Linq;
8+
using Microsoft.EntityFrameworkCore.Internal;
9+
using Sample.MySql.multi;
810
using ShardingCore.Bootstrappers;
911

1012
namespace Sample.MySql
@@ -21,6 +23,8 @@ public static void DbSeed(this IApplicationBuilder app)
2123
{
2224
using (var scope=app.ApplicationServices.CreateScope())
2325
{
26+
var otherDbContext =scope.ServiceProvider.GetService<OtherDbContext>();
27+
var any = otherDbContext.MyUsers.Any();
2428
var virtualDbContext =scope.ServiceProvider.GetService<DefaultShardingDbContext>();
2529
if (!virtualDbContext.Set<SysUserMod>().Any())
2630
{
@@ -51,6 +55,13 @@ public static void DbSeed(this IApplicationBuilder app)
5155

5256
}
5357
}
58+
59+
// using (var scope=app.ApplicationServices.CreateScope())
60+
// {
61+
//
62+
// var virtualDbContext =scope.ServiceProvider.GetService<DefaultShardingDbContext>();
63+
// var any = virtualDbContext.Set<SysUserMod>().Any();
64+
// }
5465
//using (var scope = app.ApplicationServices.CreateScope())
5566
//{
5667
// var dbContext = scope.ServiceProvider.GetService<DefaultShardingDbContext>();

samples/Sample.MySql/Sample.MySql.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
</PropertyGroup>
88

99
<ItemGroup>
10-
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.6">
10+
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.7">
1111
<PrivateAssets>all</PrivateAssets>
1212
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
1313
</PackageReference>

samples/Sample.MySql/Startup.cs

Lines changed: 104 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Microsoft.EntityFrameworkCore.Migrations;
44
using Sample.MySql.DbContexts;
55
using Sample.MySql.Domain.Entities;
6+
using Sample.MySql.multi;
67
using Sample.MySql.Shardings;
78
using ShardingCore;
89
using ShardingCore.Bootstrappers;
@@ -11,6 +12,7 @@
1112
using ShardingCore.EFCores;
1213
using ShardingCore.Extensions;
1314
using ShardingCore.Helpers;
15+
using ShardingCore.Sharding.ReadWriteConfigurations;
1416
using ShardingCore.TableExists;
1517
using ShardingCore.TableExists.Abstractions;
1618

@@ -37,8 +39,10 @@ public class Startup
3739
{
3840
public static readonly ILoggerFactory efLogger = LoggerFactory.Create(builder =>
3941
{
40-
builder.AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
42+
builder.AddFilter((category, level) =>
43+
category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information).AddConsole();
4144
});
45+
4246
public Startup(IConfiguration configuration)
4347
{
4448
Configuration = configuration;
@@ -61,52 +65,90 @@ public void ConfigureServices(IServiceCollection services)
6165
// op.AddShardingTableRoute<SysUserModVirtualTableRoute>();
6266
// op.AddShardingTableRoute<SysUserSalaryVirtualTableRoute>();
6367
// });
64-
68+
services.AddMultiShardingDbContext<OtherDbContext>()
69+
.UseRouteConfig(op => { op.AddShardingTableRoute<MyUserRoute>(); })
70+
.UseConfig(o =>
71+
{
72+
o.ThrowIfQueryRouteNotMatch = false;
73+
o.UseShardingQuery((conStr, builder) =>
74+
{
75+
builder.UseMySql(conStr, new MySqlServerVersion(new Version()))
76+
.UseLoggerFactory(efLogger)
77+
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
78+
});
79+
o.UseShardingTransaction((connection, builder) =>
80+
{
81+
builder
82+
.UseMySql(connection, new MySqlServerVersion(new Version()))
83+
.UseLoggerFactory(efLogger)
84+
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
85+
});
86+
o.UseShardingMigrationConfigure(b =>
87+
{
88+
b.ReplaceService<IMigrationsSqlGenerator, ShardingMySqlMigrationsSqlGenerator>();
89+
});
90+
o.AddDefaultDataSource("ds0",
91+
"server=127.0.0.1;port=3306;database=dbdbdx;userid=root;password=root;");
92+
}).AddShardingCore();
6593
services.AddSingleton<IShardingRuntimeContext>(sp =>
6694
{
67-
Stopwatch stopwatch=Stopwatch.StartNew();
68-
95+
Stopwatch stopwatch = Stopwatch.StartNew();
96+
6997
var shardingRuntimeContext = new ShardingRuntimeBuilder<DefaultShardingDbContext>()
7098
.UseRouteConfig(o =>
7199
{
72100
o.AddShardingTableRoute<SysUserLogByMonthRoute>();
73101
o.AddShardingTableRoute<SysUserModVirtualTableRoute>();
74-
o.AddShardingDataSourceRoute<SysUserModVirtualDataSourceRoute>();
102+
o.AddShardingDataSourceRoute<SysUserModVirtualDataSourceRoute>();
75103
}).UseConfig(o =>
76104
{
77105
o.ThrowIfQueryRouteNotMatch = false;
78-
o.UseShardingQuery((conStr,builder)=>
106+
o.UseShardingQuery((conStr, builder) =>
79107
{
80108
builder.UseMySql(conStr, new MySqlServerVersion(new Version()))
81-
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
82109
.UseLoggerFactory(efLogger)
83-
.EnableSensitiveDataLogging();
110+
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
84111
});
85112
o.UseShardingTransaction((connection, builder) =>
86113
{
87114
builder
88-
.UseMySql(connection, new MySqlServerVersion(new Version())).
89-
UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
115+
.UseMySql(connection, new MySqlServerVersion(new Version()))
90116
.UseLoggerFactory(efLogger)
91-
.EnableSensitiveDataLogging();
117+
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
92118
});
93-
o.AddDefaultDataSource("ds0", "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;");
94-
o.AddExtraDataSource(sp=>new Dictionary<string, string>()
119+
o.AddDefaultDataSource("ds0",
120+
"server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;");
121+
o.AddExtraDataSource(sp => new Dictionary<string, string>()
95122
{
96-
{"ds1", "server=127.0.0.1;port=3306;database=dbdbd1;userid=root;password=root;"},
97-
{"ds2", "server=127.0.0.1;port=3306;database=dbdbd2;userid=root;password=root;"}
123+
{ "ds1", "server=127.0.0.1;port=3306;database=dbdbd1;userid=root;password=root;" },
124+
{ "ds2", "server=127.0.0.1;port=3306;database=dbdbd2;userid=root;password=root;" }
98125
});
126+
o.AddReadWriteSeparation(sp =>
127+
{
128+
return new Dictionary<string, IEnumerable<string>>()
129+
{
130+
{
131+
"ds0",
132+
new[]
133+
{
134+
"server=127.0.0.1;port=3306;database=dbdbd0_0;userid=root;password=root;"
135+
}
136+
}
137+
};
138+
}, defaultEnable: true, readStrategyEnum: ReadStrategyEnum.Loop,
139+
readConnStringGetStrategy: ReadConnStringGetStrategyEnum.LatestEveryTime);
99140
o.UseShardingMigrationConfigure(b =>
100141
{
101142
b.ReplaceService<IMigrationsSqlGenerator, ShardingMySqlMigrationsSqlGenerator>();
102143
});
103-
}).ReplaceService<ITableEnsureManager,MySqlTableEnsureManager>(ServiceLifetime.Singleton)
144+
})//.ReplaceService<ITableEnsureManager, MySqlTableEnsureManager>(ServiceLifetime.Singleton)
104145
.Build(sp);
105146
stopwatch.Stop();
106-
Console.WriteLine("ShardingRuntimeContext build:"+stopwatch.ElapsedMilliseconds);
147+
Console.WriteLine("ShardingRuntimeContext build:" + stopwatch.ElapsedMilliseconds);
107148
return shardingRuntimeContext;
108149
});
109-
services.AddDbContext<DefaultShardingDbContext>(ShardingCoreExtension.UseDefaultSharding<DefaultShardingDbContext>);
150+
services.AddDbContext<DefaultShardingDbContext>(ShardingCoreExtension
151+
.UseMutliDefaultSharding<DefaultShardingDbContext>);
110152
// services.AddShardingDbContext<DefaultShardingDbContext>()
111153
// .AddEntityConfig(o =>
112154
// {
@@ -151,29 +193,56 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
151193
{
152194
app.UseDeveloperExceptionPage();
153195
}
154-
app.ApplicationServices.UseAutoShardingCreate();
155-
var shardingRuntimeContext = app.ApplicationServices.GetRequiredService<IShardingRuntimeContext>();
156-
var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
157-
var entityMetadata = entityMetadataManager.TryGet<SysUserMod>();
158-
using (var scope = app.ApplicationServices.CreateScope())
196+
197+
var shardingRuntimeContextManager = app.ApplicationServices.GetRequiredService<IShardingRuntimeContextManager>();
198+
var shardingRuntimeContexts = shardingRuntimeContextManager.GetAll();
199+
foreach (var keyValuePair in shardingRuntimeContexts)
159200
{
160-
var defaultShardingDbContext = scope.ServiceProvider.GetService<DefaultShardingDbContext>();
161-
// if (defaultShardingDbContext.Database.GetPendingMigrations().Any())
162-
{
163-
defaultShardingDbContext.Database.Migrate();
164-
}
201+
keyValuePair.Value.UseAutoShardingCreate();
202+
keyValuePair.Value.UseAutoTryCompensateTable();
165203
}
204+
// app.ApplicationServices.UseAutoShardingCreate();
205+
// var shardingRuntimeContext = app.ApplicationServices.GetRequiredService<IShardingRuntimeContext>();
206+
// var entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();
207+
// var entityMetadata = entityMetadataManager.TryGet<SysUserMod>();
208+
// using (var scope = app.ApplicationServices.CreateScope())
209+
// {
210+
// var defaultShardingDbContext = scope.ServiceProvider.GetService<DefaultShardingDbContext>();
211+
// // if (defaultShardingDbContext.Database.GetPendingMigrations().Any())
212+
// {
213+
// try
214+
// {
215+
//
216+
// defaultShardingDbContext.Database.Migrate();
217+
// }
218+
// catch (Exception e)
219+
// {
220+
// }
221+
// }
222+
// }
223+
// using (var scope = app.ApplicationServices.CreateScope())
224+
// {
225+
// var defaultShardingDbContext = scope.ServiceProvider.GetService<OtherDbContext>();
226+
// // if (defaultShardingDbContext.Database.GetPendingMigrations().Any())
227+
// {
228+
// try
229+
// {
230+
//
231+
// defaultShardingDbContext.Database.Migrate();
232+
// }
233+
// catch (Exception e)
234+
// {
235+
// }
236+
// }
237+
// }
238+
//
239+
// app.ApplicationServices.UseAutoTryCompensateTable(12);
166240

167-
app.ApplicationServices.UseAutoTryCompensateTable(12);
168-
169241
app.UseRouting();
170242

171243
app.UseAuthorization();
172244

173-
app.UseEndpoints(endpoints =>
174-
{
175-
endpoints.MapControllers();
176-
});
245+
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
177246
// for (int i = 1; i < 500; i++)
178247
// {
179248
// using (var conn = new MySqlConnection(
@@ -187,4 +256,4 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
187256
app.DbSeed();
188257
}
189258
}
190-
}
259+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
using System.ComponentModel.DataAnnotations.Schema;
2+
3+
namespace Sample.MySql.multi;
4+
[Table("MyUser")]
5+
public class MyUser
6+
{
7+
public string Id { get; set; }
8+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
using ShardingCore.Core.EntityMetadatas;
2+
using ShardingCore.VirtualRoutes.Mods;
3+
4+
namespace Sample.MySql.multi;
5+
6+
public class MyUserRoute:AbstractSimpleShardingModKeyStringVirtualTableRoute<MyUser>
7+
{
8+
public MyUserRoute() : base(1, 3)
9+
{
10+
}
11+
12+
public override void Configure(EntityMetadataTableBuilder<MyUser> builder)
13+
{
14+
builder.ShardingProperty(o => o.Id);
15+
}
16+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
using Microsoft.EntityFrameworkCore;
2+
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
3+
using ShardingCore.Sharding;
4+
using ShardingCore.Sharding.Abstractions;
5+
6+
namespace Sample.MySql.multi;
7+
8+
public class OtherDbContext:AbstractShardingDbContext,IShardingTableDbContext
9+
{
10+
public DbSet<MyUser> MyUsers { get; set; }
11+
public OtherDbContext(DbContextOptions<OtherDbContext> options) : base(options)
12+
{
13+
}
14+
15+
public IRouteTail RouteTail { get; set; }
16+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
using System;
2+
using System.Collections.Generic;
3+
4+
namespace ShardingCore.Core.RuntimeContexts
5+
{
6+
public interface IShardingRuntimeContextManager
7+
{
8+
/// <summary>
9+
/// 尝试获取注册的dbcontext type对应的 没有返回null
10+
/// </summary>
11+
/// <param name="dbContextType"></param>
12+
/// <returns></returns>
13+
IShardingRuntimeContext TryGet(Type dbContextType);
14+
15+
IReadOnlyDictionary<Type, IShardingRuntimeContext> GetAll();
16+
}
17+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System;
2+
using System.Collections;
3+
using System.Collections.Generic;
4+
using System.Collections.Immutable;
5+
using System.Linq;
6+
7+
namespace ShardingCore.Core.RuntimeContexts
8+
{
9+
10+
public class ShardingRuntimeContextManager:IShardingRuntimeContextManager
11+
{
12+
private readonly ImmutableDictionary<Type, IShardingRuntimeContext> _caches;
13+
public ShardingRuntimeContextManager(IEnumerable<IShardingRuntimeContext> shardingRuntimeContexts)
14+
{
15+
_caches = shardingRuntimeContexts.ToImmutableDictionary(o => o.DbContextType, o => o);
16+
}
17+
public IShardingRuntimeContext TryGet(Type dbContextType)
18+
{
19+
if (_caches.TryGetValue(dbContextType, out var shardingRuntimeContext))
20+
{
21+
return shardingRuntimeContext;
22+
}
23+
24+
return null;
25+
}
26+
27+
public IReadOnlyDictionary<Type, IShardingRuntimeContext> GetAll()
28+
{
29+
return _caches;
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)