优化executor获取scoped的bug

This commit is contained in:
xuejiaming 2023-11-24 15:56:32 +08:00
parent e02225e32e
commit 21aebbca5e
15 changed files with 103 additions and 7 deletions

View File

@ -497,6 +497,19 @@ namespace Sample.MySql.Controllers
// var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync(); // var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync();
return Ok(sysUserMods); return Ok(sysUserMods);
} }
[HttpGet]
public async Task<IActionResult> Get211()
{
var sysUserMod = new SysUserMod();
sysUserMod.Id = "xxxx111x";
sysUserMod.Age = 1;
sysUserMod.Name = "ds0";
await _defaultTableDbContext.AddAsync(sysUserMod);
await _defaultTableDbContext.SaveChangesAsync();
// var sysUserMods1 = await _defaultTableDbContext.Set<SysUserMod>().FromSqlRaw("select * from SysUserMod where id='2'").ToListAsync();
// var sysUserMods2 = await _defaultTableDbContext.Set<SysTest>().FromSqlRaw("select * from SysTest where id='2'").ToListAsync();
return Ok();
}
// public void batachSave() // public void batachSave()
// { // {

View File

@ -53,6 +53,7 @@ namespace Sample.MySql.DbContexts
// modelBuilder.Entity<SysTest>().HasData(new SysTest() { Id = "1", UserId = "123" }); // modelBuilder.Entity<SysTest>().HasData(new SysTest() { Id = "1", UserId = "123" });
// modelBuilder.Entity<TestMod>().ToTable(nameof(TestMod)); // modelBuilder.Entity<TestMod>().ToTable(nameof(TestMod));
// modelBuilder.Entity<SysTest>().ToTable("xxx"); // modelBuilder.Entity<SysTest>().ToTable("xxx");
} }

View File

@ -1,4 +1,5 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Sample.MySql.Domain.Maps; using Sample.MySql.Domain.Maps;
namespace Sample.MySql.DbContexts namespace Sample.MySql.DbContexts

View File

@ -0,0 +1,8 @@
namespace Sample.MySql
{
public class MyCurrentUser
{
}
}

View File

@ -0,0 +1,17 @@
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
namespace Sample.MySql
{
public class MySaveChangeInterceptor:SaveChangesInterceptor
{
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(DbContextEventData eventData, InterceptionResult<int> result,
CancellationToken cancellationToken = new CancellationToken())
{
var myCurrentUser = eventData.Context.GetService<MyCurrentUser>();
Console.WriteLine("1"+myCurrentUser!=null);
return base.SavingChangesAsync(eventData, result, cancellationToken);
}
}
}

View File

@ -154,6 +154,11 @@ namespace Sample.MySql
// .EnableSensitiveDataLogging(); // .EnableSensitiveDataLogging();
//.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); //.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
}); });
o.UseExecutorDbContextConfigure(builder =>
{
builder
.AddInterceptors(new MySaveChangeInterceptor());
});
o.AddDefaultDataSource("ds0", o.AddDefaultDataSource("ds0",
"server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;"); "server=127.0.0.1;port=3306;database=dbdbd0;userid=root;password=root;");
o.AddExtraDataSource(sp => new Dictionary<string, string>() o.AddExtraDataSource(sp => new Dictionary<string, string>()
@ -168,6 +173,7 @@ namespace Sample.MySql
}).ReplaceService<IModelCacheLockerProvider, DicModelCacheLockerProvider>() }).ReplaceService<IModelCacheLockerProvider, DicModelCacheLockerProvider>()
.ReplaceService<IDataSourceInitializer, DataSourceInitializer>() .ReplaceService<IDataSourceInitializer, DataSourceInitializer>()
.AddShardingCore(); .AddShardingCore();
services.AddScoped<MyCurrentUser>();
// services.AddDbContext<DefaultShardingDbContext>(ShardingCoreExtension // services.AddDbContext<DefaultShardingDbContext>(ShardingCoreExtension
// .UseMutliDefaultSharding<DefaultShardingDbContext>); // .UseMutliDefaultSharding<DefaultShardingDbContext>);
// services.AddShardingDbContext<DefaultShardingDbContext>() // services.AddShardingDbContext<DefaultShardingDbContext>()

View File

@ -0,0 +1,38 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// using System.Threading.Tasks;
// using Microsoft.EntityFrameworkCore;
// using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
// using ShardingCore.Core.DbContextCreator;
// using ShardingCore.Core.ServiceProviders;
// using ShardingCore.Sharding.Abstractions;
//
// namespace ShardingCore.Core.DbContextCreator
// {
// /// <summary>
// /// dbcontext创建者
// /// </summary>
// /// Author: xjm
// /// Created: 2022/4/2 21:12:17
// /// Email: 326308290@qq.com
// public interface IAsyncDbContextCreator
// {
// /// <summary>
// /// 创建dbcontext
// /// </summary>
// /// <param name="shellDbContext">最外部的dbcontext也就是壳不具备真正的执行</param>
// /// <param name="shardingDbContextOptions">返回dbcontext的配置路由等信息</param>
// /// <returns></returns>
// DbContext CreateDbContext(DbContext shellDbContext, ShardingDbContextOptions shardingDbContextOptions);
// // DbContext CreateDbContext(DbContext shellDbContext, ShardingDbContextOptions shardingDbContextOptions);
//
// /// <summary>
// /// 返回shell db context 框架如何获取db context
// /// </summary>
// /// <param name="shardingProvider"></param>
// /// <returns></returns>
// DbContext GetShellDbContext(IShardingProvider shardingProvider);
// }
// }

View File

@ -26,6 +26,7 @@ namespace ShardingCore.Core.DbContextCreator
/// <param name="shardingDbContextOptions">返回dbcontext的配置路由等信息</param> /// <param name="shardingDbContextOptions">返回dbcontext的配置路由等信息</param>
/// <returns></returns> /// <returns></returns>
DbContext CreateDbContext(DbContext shellDbContext, ShardingDbContextOptions shardingDbContextOptions); DbContext CreateDbContext(DbContext shellDbContext, ShardingDbContextOptions shardingDbContextOptions);
// DbContext CreateDbContext(DbContext shellDbContext, ShardingDbContextOptions shardingDbContextOptions);
/// <summary> /// <summary>
/// 返回shell db context 框架如何获取db context /// 返回shell db context 框架如何获取db context

View File

@ -1,5 +1,6 @@
using System; using System;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using ShardingCore.Core.DbContextTypeAwares; using ShardingCore.Core.DbContextTypeAwares;
using ShardingCore.Core.ServiceProviders; using ShardingCore.Core.ServiceProviders;
@ -15,15 +16,19 @@ namespace ShardingCore.Core.DbContextOptionBuilderCreator
_shardingProvider = shardingProvider; _shardingProvider = shardingProvider;
_dbContextTypeAware = dbContextTypeAware; _dbContextTypeAware = dbContextTypeAware;
} }
public DbContextOptionsBuilder CreateDbContextOptionBuilder() public DbContextOptionsBuilder CreateDbContextOptionBuilder(DbContext shellDbContext)
{ {
var dbContextType = _dbContextTypeAware.GetContextType(); var dbContextType = _dbContextTypeAware.GetContextType();
Type type = typeof(DbContextOptionsBuilder<>); Type type = typeof(DbContextOptionsBuilder<>);
type = type.MakeGenericType(dbContextType); type = type.MakeGenericType(dbContextType);
var dbContextOptionsBuilder = (DbContextOptionsBuilder)Activator.CreateInstance(type); var dbContextOptionsBuilder = (DbContextOptionsBuilder)Activator.CreateInstance(type);
if (_shardingProvider.ApplicationServiceProvider != null) if (dbContextOptionsBuilder!=null&&shellDbContext != null)
{ {
dbContextOptionsBuilder.UseApplicationServiceProvider(_shardingProvider.ApplicationServiceProvider); var applicationServiceProvider = shellDbContext.GetService<IDbContextOptions>()?.FindExtension<CoreOptionsExtension>()?.ApplicationServiceProvider;
if (applicationServiceProvider != null)
{
dbContextOptionsBuilder.UseApplicationServiceProvider(applicationServiceProvider);
}
} }
return dbContextOptionsBuilder; return dbContextOptionsBuilder;
} }

View File

@ -4,6 +4,6 @@ namespace ShardingCore.Core.DbContextOptionBuilderCreator
{ {
public interface IDbContextOptionBuilderCreator public interface IDbContextOptionBuilderCreator
{ {
DbContextOptionsBuilder CreateDbContextOptionBuilder(); DbContextOptionsBuilder CreateDbContextOptionBuilder(DbContext shellDbContext);
} }
} }

View File

@ -127,7 +127,7 @@ namespace ShardingCore.Helpers
{ {
var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource(); var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
var shardingConfigOptions = shardingRuntimeContext.GetShardingConfigOptions(); var shardingConfigOptions = shardingRuntimeContext.GetShardingConfigOptions();
var dbContextOptionBuilder =shardingRuntimeContext.GetDbContextOptionBuilderCreator().CreateDbContextOptionBuilder(); var dbContextOptionBuilder =shardingRuntimeContext.GetDbContextOptionBuilderCreator().CreateDbContextOptionBuilder(null);
var connectionString = virtualDataSource.GetConnectionString(dataSourceName); var connectionString = virtualDataSource.GetConnectionString(dataSourceName);
virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder); virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder);
shardingConfigOptions.ShardingMigrationConfigure?.Invoke(dbContextOptionBuilder); shardingConfigOptions.ShardingMigrationConfigure?.Invoke(dbContextOptionBuilder);

View File

@ -150,7 +150,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
{ {
//先创建dbcontext option builder //先创建dbcontext option builder
var dbContextOptionBuilderCreator = _shardingRuntimeContext.GetDbContextOptionBuilderCreator(); var dbContextOptionBuilderCreator = _shardingRuntimeContext.GetDbContextOptionBuilderCreator();
var dbContextOptionsBuilder = dbContextOptionBuilderCreator.CreateDbContextOptionBuilder() var dbContextOptionsBuilder = dbContextOptionBuilderCreator.CreateDbContextOptionBuilder(_shardingShellDbContext)
.UseShardingOptions(_shardingRuntimeContext); .UseShardingOptions(_shardingRuntimeContext);
if (IsDefault) if (IsDefault)

View File

@ -149,7 +149,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
CreateDbContextStrategyEnum strategy) CreateDbContextStrategyEnum strategy)
{ {
var dbContextOptionBuilder = _shardingRuntimeContext.GetDbContextOptionBuilderCreator() var dbContextOptionBuilder = _shardingRuntimeContext.GetDbContextOptionBuilderCreator()
.CreateDbContextOptionBuilder(); .CreateDbContextOptionBuilder(_shardingDbContext);
var connectionString = _actualConnectionStringManager.GetConnectionString(dataSourceName, var connectionString = _actualConnectionStringManager.GetConnectionString(dataSourceName,
CreateDbContextStrategyEnum.IndependentConnectionWrite == strategy); CreateDbContextStrategyEnum.IndependentConnectionWrite == strategy);
_virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder) _virtualDataSource.UseDbContextOptionsBuilder(connectionString, dbContextOptionBuilder)

View File

@ -27,6 +27,9 @@
<Compile Include="..\..\src\ShardingCore\**\*.cs" /> <Compile Include="..\..\src\ShardingCore\**\*.cs" />
<Compile Remove="..\..\src\ShardingCore\obj\**" /> <Compile Remove="..\..\src\ShardingCore\obj\**" />
<Compile Remove="..\..\src\ShardingCore\bin\**" /> <Compile Remove="..\..\src\ShardingCore\bin\**" />
<Compile Update="..\..\src\ShardingCore\Core\DbContextOptionBuilderCreator\ShardingDbContextOptions.cs">
<Link>Core\DbContextOptionBuilderCreator\ShardingDbContextOptions.cs</Link>
</Compile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.6" />

View File

@ -26,6 +26,9 @@
<Compile Include="..\..\src\ShardingCore\**\*.cs" /> <Compile Include="..\..\src\ShardingCore\**\*.cs" />
<Compile Remove="..\..\src\ShardingCore\obj\**" /> <Compile Remove="..\..\src\ShardingCore\obj\**" />
<Compile Remove="..\..\src\ShardingCore\bin\**" /> <Compile Remove="..\..\src\ShardingCore\bin\**" />
<Compile Update="..\..\src\ShardingCore\Core\DbContextCreator\IAsyncDbContextCreator.cs">
<Link>Core\DbContextCreator\IAsyncDbContextCreator.cs</Link>
</Compile>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>