完成大部分重构

This commit is contained in:
xuejiaming 2022-07-01 17:46:49 +08:00
parent fea8e9a781
commit a288c517ba
45 changed files with 967 additions and 833 deletions

View File

@ -44,14 +44,16 @@ namespace ShardingCore.Bootstrappers
// private readonly string _virtualTableName;
// private readonly Expression<Func<TEntity,bool>> _queryFilterExpression;
private readonly Type _shardingEntityType;
private readonly IShardingEntityConfigOptions _shardingEntityConfigOptions;
private readonly IShardingProvider _shardingProvider;
private readonly IShardingRouteConfigOptions _shardingRouteConfigOptions;
private readonly IVirtualDataSourceRouteManager _virtualDataSourceRouteManager;
private readonly ITableRouteManager _tableRouteManager;
private readonly IEntityMetadataManager _entityMetadataManager;
private readonly IJobManager _jobManager;
public EntityMetadataInitializer(
IShardingEntityConfigOptions shardingEntityConfigOptions,
IShardingProvider shardingProvider,
IShardingRouteConfigOptions shardingRouteConfigOptions,
IVirtualDataSourceRouteManager virtualDataSourceRouteManager,
ITableRouteManager tableRouteManager,
IEntityMetadataManager entityMetadataManager,
@ -62,7 +64,8 @@ namespace ShardingCore.Bootstrappers
// _entityType = entityMetadataEnsureParams.EntityType;
// _virtualTableName = entityMetadataEnsureParams.VirtualTableName;
// _queryFilterExpression = entityMetadataEnsureParams.EntityType.GetAnnotations().FirstOrDefault(o=>o.Name== QueryFilter)?.Value as Expression<Func<TEntity, bool>>;
_shardingEntityConfigOptions = shardingEntityConfigOptions;
_shardingProvider = shardingProvider;
_shardingRouteConfigOptions = shardingRouteConfigOptions;
_virtualDataSourceRouteManager = virtualDataSourceRouteManager;
_tableRouteManager = tableRouteManager;
_entityMetadataManager = entityMetadataManager;
@ -81,7 +84,7 @@ namespace ShardingCore.Bootstrappers
if (!_entityMetadataManager.AddEntityMetadata(entityMetadata))
throw new ShardingCoreInvalidOperationException($"repeat add entity metadata {_shardingEntityType.FullName}");
//设置标签
if (_shardingEntityConfigOptions.TryGetVirtualDataSourceRoute<TEntity>(out var virtualDataSourceRouteType))
if (_shardingRouteConfigOptions.TryGetVirtualDataSourceRoute<TEntity>(out var virtualDataSourceRouteType))
{
var creatEntityMetadataDataSourceBuilder = EntityMetadataDataSourceBuilder<TEntity>.CreateEntityMetadataDataSourceBuilder(entityMetadata);
//配置属性分库信息
@ -89,7 +92,7 @@ namespace ShardingCore.Bootstrappers
var dataSourceRoute = CreateVirtualDataSourceRoute(virtualDataSourceRouteType);
if (dataSourceRoute is IEntityMetadataAutoBindInitializer entityMetadataAutoBindInitializer)
{
entityMetadataAutoBindInitializer.Initialize(entityMetadata);
entityMetadataAutoBindInitializer.Initialize(entityMetadata,_shardingProvider);
}
//配置分库信息
if(dataSourceRoute is IEntityMetadataDataSourceConfiguration<TEntity> entityMetadataDataSourceConfiguration)
@ -100,7 +103,7 @@ namespace ShardingCore.Bootstrappers
entityMetadata.CheckShardingDataSourceMetadata();
}
if (_shardingEntityConfigOptions.TryGetVirtualTableRoute<TEntity>(out var virtualTableRouteType))
if (_shardingRouteConfigOptions.TryGetVirtualTableRoute<TEntity>(out var virtualTableRouteType))
{
if (!typeof(TShardingDbContext).IsShardingTableDbContext())
throw new ShardingCoreInvalidOperationException(
@ -112,7 +115,7 @@ namespace ShardingCore.Bootstrappers
var virtualTableRoute = CreateVirtualTableRoute(virtualTableRouteType);
if (virtualTableRoute is IEntityMetadataAutoBindInitializer entityMetadataAutoBindInitializer)
{
entityMetadataAutoBindInitializer.Initialize(entityMetadata);
entityMetadataAutoBindInitializer.Initialize(entityMetadata,_shardingProvider);
}
//配置分表信息
if (virtualTableRoute is IEntityMetadataTableConfiguration<TEntity> createEntityMetadataTableConfiguration)
@ -135,14 +138,14 @@ namespace ShardingCore.Bootstrappers
private IVirtualDataSourceRoute<TEntity> CreateVirtualDataSourceRoute(Type virtualRouteType)
{
var instance = ShardingRuntimeContext.GetInstance().CreateInstance(virtualRouteType);
var instance = _shardingProvider.CreateInstance(virtualRouteType);
return (IVirtualDataSourceRoute<TEntity>)instance;
}
private IVirtualTableRoute<TEntity> CreateVirtualTableRoute(Type virtualRouteType)
{
var instance = ShardingRuntimeContext.GetInstance().CreateInstance(virtualRouteType);
var instance = _shardingProvider.CreateInstance(virtualRouteType);
return (IVirtualTableRoute<TEntity>)instance;
}
}

View File

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ShardingCore.Core;
using ShardingCore.Extensions;
using ShardingCore.Jobs;
using ShardingCore.Jobs.Abstaractions;
@ -20,15 +21,15 @@ namespace ShardingCore.Bootstrappers
public class ShardingBootstrapper : IShardingBootstrapper
{
private readonly ILogger<ShardingBootstrapper> _logger;
private readonly IServiceProvider _internalServiceProvider;
private readonly IShardingProvider _shardingProvider;
private readonly IDbContextTypeCollector _dbContextTypeCollector;
private readonly IJobManager _jobManager;
private readonly DoOnlyOnce _doOnlyOnce = new DoOnlyOnce();
public ShardingBootstrapper(IServiceProvider internalServiceProvider,IDbContextTypeCollector dbContextTypeCollector,IJobManager jobManager)
public ShardingBootstrapper(IShardingProvider shardingProvider,IDbContextTypeCollector dbContextTypeCollector,IJobManager jobManager)
{
_logger = InternalLoggerFactory.DefaultFactory .CreateLogger<ShardingBootstrapper>();
_internalServiceProvider = internalServiceProvider;
_logger = InternalLoggerFactory.DefaultFactory.CreateLogger<ShardingBootstrapper>();
_shardingProvider = shardingProvider;
_dbContextTypeCollector = dbContextTypeCollector;
_jobManager = jobManager;
}
@ -40,8 +41,9 @@ namespace ShardingCore.Bootstrappers
if (!_doOnlyOnce.IsUnDo())
return;
_logger.LogDebug("sharding core starting......");
var instance = (IShardingDbContextBootstrapper)ActivatorUtilities.CreateInstance(_internalServiceProvider,typeof(ShardingDbContextBootstrapper<>).GetGenericType0(_dbContextTypeCollector.ShardingDbContextType));
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");
@ -50,7 +52,7 @@ namespace ShardingCore.Bootstrappers
{
Task.Factory.StartNew(async () =>
{
await _internalServiceProvider.GetRequiredService<JobRunnerService>().StartAsync();
await _shardingProvider.GetRequiredService<JobRunnerService>().StartAsync();
}, TaskCreationOptions.LongRunning);
}
}

View File

@ -38,30 +38,27 @@ namespace ShardingCore.Bootstrappers
public class ShardingDbContextBootstrapper<TShardingDbContext> : IShardingDbContextBootstrapper
where TShardingDbContext : DbContext, IShardingDbContext
{
private readonly IServiceProvider _internalServiceProvider;
private readonly IShardingEntityConfigOptions _entityConfigOptions;
private readonly IShardingProvider _shardingProvider;
private readonly IShardingRouteConfigOptions _routeConfigOptions;
private readonly IEntityMetadataManager _entityMetadataManager;
private readonly IParallelTableManager _parallelTableManager;
private readonly IVirtualDataSource _virtualDataSource;
// private readonly ITrackerManager<TShardingDbContext> _trackerManager;
private readonly Type _shardingDbContextType;
public ShardingDbContextBootstrapper(
IServiceProvider internalServiceProvider,
IShardingEntityConfigOptions entityConfigOptions,
IShardingProvider shardingProvider,
IShardingRouteConfigOptions routeConfigOptions,
IEntityMetadataManager entityMetadataManager,
IParallelTableManager parallelTableManager,
IVirtualDataSource virtualDataSource
IParallelTableManager parallelTableManager
)
{
_shardingDbContextType = typeof(TShardingDbContext);
_internalServiceProvider = internalServiceProvider;
_entityConfigOptions = entityConfigOptions;
_shardingProvider = shardingProvider;
_routeConfigOptions = routeConfigOptions;
_entityMetadataManager = entityMetadataManager;
_parallelTableManager = parallelTableManager;
_virtualDataSource = virtualDataSource;
}
/// <summary>
@ -76,15 +73,14 @@ namespace ShardingCore.Bootstrappers
private void InitializeEntityMetadata()
{
var shardingEntities = _entityConfigOptions.GetShardingTableRouteTypes()
.Concat(_entityConfigOptions.GetShardingDataSourceRouteTypes()).ToHashSet();
var shardingEntities = _routeConfigOptions.GetShardingTableRouteTypes()
.Concat(_routeConfigOptions.GetShardingDataSourceRouteTypes()).ToHashSet();
foreach (var entityType in shardingEntities)
{
var entityMetadataInitializerType =
typeof(EntityMetadataInitializer<,>).GetGenericType1(_shardingDbContextType, entityType);
var entityMetadataInitializer =
(IEntityMetadataInitializer)ActivatorUtilities.CreateInstance(_internalServiceProvider,entityMetadataInitializerType);
var entityMetadataInitializer =(IEntityMetadataInitializer)_shardingProvider.CreateInstance(entityMetadataInitializerType);
entityMetadataInitializer.Initialize();
}
@ -92,7 +88,7 @@ namespace ShardingCore.Bootstrappers
private void InitializeParallelTables()
{
foreach (var parallelTableGroupNode in _entityConfigOptions.GetParallelTableGroupNodes())
foreach (var parallelTableGroupNode in _routeConfigOptions.GetParallelTableGroupNodes())
{
var parallelTableComparerType = parallelTableGroupNode.GetEntities()
.FirstOrDefault(o => !_entityMetadataManager.IsShardingTable(o.Type));

View File

@ -4,6 +4,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using ShardingCore.Extensions;
using ShardingCore.Sharding.Abstractions;
@ -78,5 +79,15 @@ namespace ShardingCore.Core.EntityMetadatas
{
return _caches.Keys.ToList();
}
public bool TryInitModel(IEntityType efEntityType)
{
if (_caches.TryGetValue(efEntityType.ClrType,out var metadata))
{
metadata.SetEntityModel(efEntityType);
return true;
}
return false;
}
}
}

View File

@ -5,10 +5,12 @@
/// </summary>
public interface IEntityMetadataAutoBindInitializer
{
IShardingProvider RouteShardingProvider { get; }
/// <summary>
/// 初始化 在启动时会被调用并且将对象元数据绑定到对应的路由上面
/// </summary>
/// <param name="entityMetadata"></param>
void Initialize(EntityMetadata entityMetadata);
/// <param name="shardingProvider"></param>
void Initialize(EntityMetadata entityMetadata,IShardingProvider shardingProvider);
}
}

View File

@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using ShardingCore.Sharding.Abstractions;
namespace ShardingCore.Core.EntityMetadatas
@ -44,5 +45,7 @@ namespace ShardingCore.Core.EntityMetadatas
bool IsSharding(Type entityType);
List<Type> GetAllShardingEntities();
bool TryInitModel(IEntityType efEntityType);
}
}

View File

@ -0,0 +1,10 @@
using System;
namespace ShardingCore.Core
{
public interface IShardingProvider
{
object GetService(Type serviceType);
}
}

View File

@ -38,9 +38,11 @@ namespace ShardingCore.Core
void UseLogfactory(ILoggerFactory loggerFactory);
void WithApplicationServiceProvider(IServiceProvider applicationServiceProvider);
void UseApplicationServiceProvider(IServiceProvider applicationServiceProvider);
void Initialize();
object GetService(Type serviceType);
TService GetService<TService>();
object GetRequiredService(Type serviceType);
TService GetRequiredService<TService>();
}
}

View File

@ -1,12 +1,12 @@
using Microsoft.EntityFrameworkCore;
using ShardingCore.Sharding.Abstractions;
namespace ShardingCore.Core.ShardingConfigurations.Abstractions
{
public interface IShardingConfigurationOptions
{
public void AddShardingGlobalConfigOptions(ShardingConfigOptions shardingConfigOptions);
public ShardingConfigOptions[] GetAllShardingGlobalConfigOptions();
}
}
// using Microsoft.EntityFrameworkCore;
// using ShardingCore.Sharding.Abstractions;
//
// namespace ShardingCore.Core.ShardingConfigurations.Abstractions
// {
// public interface IShardingConfigurationOptions
// {
// public void AddShardingGlobalConfigOptions(ShardingConfigOptions shardingConfigOptions);
//
// public ShardingConfigOptions[] GetAllShardingGlobalConfigOptions();
// }
// }

View File

@ -1,121 +0,0 @@
using Microsoft.EntityFrameworkCore;
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes;
using ShardingCore.Core.VirtualRoutes.TableRoutes;
using ShardingCore.Sharding.ParallelTables;
using System;
using System.Collections.Generic;
using System.Data.Common;
namespace ShardingCore.Core.ShardingConfigurations.Abstractions
{
public interface IShardingEntityConfigOptions
{
/// <summary>
/// 如果数据库不存在就创建并且创建表除了分表的
/// </summary>
bool EnsureCreatedWithOutShardingTable { get; set; }
/// <summary>
/// 是否需要在启动时创建分表
/// </summary>
bool? CreateShardingTableOnStart { get; set; }
/// <summary>
/// 是否在启动时创建数据库
/// </summary>
public bool? CreateDataBaseOnlyOnStart { get; set; }
/// <summary>
/// 当查询遇到没有路由被命中时是否抛出错误
/// </summary>
bool ThrowIfQueryRouteNotMatch { get; set; }
/// <summary>
/// 忽略建表时的错误
/// </summary>
bool? IgnoreCreateTableError { get; set; }
///// <summary>
///// 是否启用分表路由编译缓存(默认只缓存单个操作的也就是<![CDATA[=,>,>=,<,<=]]>)
///// default cache single filter route expression, <![CDATA[=,>,>=,<,<=]]> with sharding property
///// </summary>
//bool? EnableTableRouteCompileCache { get; set; }
///// <summary>
///// 是否启用分库路由编译缓存(默认只缓存单个操作的也就是<![CDATA[=,>,>=,<,<=]]>)
///// default cache single filter route expression, <![CDATA[=,>,>=,<,<=]]> with sharding property
///// </summary>
//bool? EnableDataSourceRouteCompileCache { get; set; }
/// <summary>
/// 添加分库路由
/// </summary>
/// <param name="routeType"></param>
void AddShardingDataSourceRoute(Type routeType);
/// <summary>
/// 添加分表路由
/// </summary>
/// <param name="routeType"></param>
void AddShardingTableRoute(Type routeType);
/// <summary>
/// 是否有虚拟表路由
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
bool HasVirtualTableRoute(Type entityType);
/// <summary>
/// 获取虚拟表路由
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
Type GetVirtualTableRouteType(Type entityType);
/// <summary>
/// 是否有虚拟库路由
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
bool HasVirtualDataSourceRoute(Type entityType);
/// <summary>
/// 获取虚拟库路由
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
Type GetVirtualDataSourceRouteType(Type entityType);
/// <summary>
/// 获取所有的分表路由类型
/// </summary>
/// <returns></returns>
ISet<Type> GetShardingTableRouteTypes();
/// <summary>
/// 获取所有的分库路由类型
/// </summary>
/// <returns></returns>
ISet<Type> GetShardingDataSourceRouteTypes();
/// <summary>
/// 平行表
/// </summary>
bool AddParallelTableGroupNode(ParallelTableGroupNode parallelTableGroupNode);
/// <summary>
/// 获取平行表
/// </summary>
/// <returns></returns>
ISet<ParallelTableGroupNode> GetParallelTableGroupNodes();
/// <summary>
/// DbContext如何通过现有connection创建
/// </summary>
Action<DbConnection, DbContextOptionsBuilder> ConnectionConfigure { get; }
/// <summary>
/// DbContext如何通过连接字符串创建
/// </summary>
Action<string, DbContextOptionsBuilder> ConnectionStringConfigure { get; }
Action<DbContextOptionsBuilder> ExecutorDbContextConfigure { get; }
Action<DbContextOptionsBuilder> ShellDbContextConfigure { get; }
/// <summary>
/// DbContext如何通过连接字符串创建
/// </summary>
public void UseShardingQuery(Action<string, DbContextOptionsBuilder> queryConfigure);
/// <summary>
/// DbContext如何通过现有connection创建
/// </summary>
public void UseShardingTransaction(Action<DbConnection, DbContextOptionsBuilder> transactionConfigure);
void UseExecutorDbContextConfigure(Action<DbContextOptionsBuilder> executorDbContextConfigure);
void UseShellDbContextConfigure(Action<DbContextOptionsBuilder> shellDbContextConfigure);
}
}

View File

@ -0,0 +1,112 @@
using Microsoft.EntityFrameworkCore;
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes;
using ShardingCore.Core.VirtualRoutes.TableRoutes;
using ShardingCore.Sharding.ParallelTables;
using System;
using System.Collections.Generic;
using System.Data.Common;
namespace ShardingCore.Core.ShardingConfigurations.Abstractions
{
public interface IShardingRouteConfigOptions
{
/// <summary>
/// 当查询遇到没有路由被命中时是否抛出错误
/// </summary>
bool ThrowIfQueryRouteNotMatch { get; set; }
// /// <summary>
// /// 如果数据库不存在就创建并且创建表除了分表的
// /// </summary>
// bool EnsureCreatedWithOutShardingTable { get; set; }
//
// /// <summary>
// /// 是否需要在启动时创建分表
// /// </summary>
// bool? CreateShardingTableOnStart { get; set; }
// /// <summary>
// /// 是否在启动时创建数据库
// /// </summary>
// public bool? CreateDataBaseOnlyOnStart { get; set; }
/// <summary>
/// 忽略建表时的错误
/// </summary>
bool? IgnoreCreateTableError { get; set; }
// ///// <summary>
// ///// 是否启用分表路由编译缓存(默认只缓存单个操作的也就是<![CDATA[=,>,>=,<,<=]]>)
// ///// default cache single filter route expression, <![CDATA[=,>,>=,<,<=]]> with sharding property
// ///// </summary>
// //bool? EnableTableRouteCompileCache { get; set; }
// ///// <summary>
// ///// 是否启用分库路由编译缓存(默认只缓存单个操作的也就是<![CDATA[=,>,>=,<,<=]]>)
// ///// default cache single filter route expression, <![CDATA[=,>,>=,<,<=]]> with sharding property
// ///// </summary>
// //bool? EnableDataSourceRouteCompileCache { get; set; }
/// <summary>
/// 添加分库路由
/// </summary>
/// <param name="routeType"></param>
void AddShardingDataSourceRoute(Type routeType);
/// <summary>
/// 添加分表路由
/// </summary>
/// <param name="routeType"></param>
void AddShardingTableRoute(Type routeType);
/// <summary>
/// 是否有虚拟表路由
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
bool HasVirtualTableRoute(Type entityType);
/// <summary>
/// 获取虚拟表路由
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
Type GetVirtualTableRouteType(Type entityType);
/// <summary>
/// 是否有虚拟库路由
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
bool HasVirtualDataSourceRoute(Type entityType);
/// <summary>
/// 获取虚拟库路由
/// </summary>
/// <param name="entityType"></param>
/// <returns></returns>
Type GetVirtualDataSourceRouteType(Type entityType);
/// <summary>
/// 获取所有的分表路由类型
/// </summary>
/// <returns></returns>
ISet<Type> GetShardingTableRouteTypes();
/// <summary>
/// 获取所有的分库路由类型
/// </summary>
/// <returns></returns>
ISet<Type> GetShardingDataSourceRouteTypes();
/// <summary>
/// 平行表
/// </summary>
bool AddParallelTableGroupNode(ParallelTableGroupNode parallelTableGroupNode);
/// <summary>
/// 获取平行表
/// </summary>
/// <returns></returns>
ISet<ParallelTableGroupNode> GetParallelTableGroupNodes();
// /// <summary>
// /// DbContext如何通过现有connection创建
// /// </summary>
// Action<DbConnection, DbContextOptionsBuilder> ConnectionConfigure { get; }
// /// <summary>
// /// DbContext如何通过连接字符串创建
// /// </summary>
// Action<string, DbContextOptionsBuilder> ConnectionStringConfigure { get; }
// Action<DbContextOptionsBuilder> ExecutorDbContextConfigure { get; }
// Action<DbContextOptionsBuilder> ShellDbContextConfigure { get; }
//
// void UseExecutorDbContextConfigure(Action<DbContextOptionsBuilder> executorDbContextConfigure);
// void UseShellDbContextConfigure(Action<DbContextOptionsBuilder> shellDbContextConfigure);
}
}

View File

@ -1,164 +1,160 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using ShardingCore.Core.ShardingConfigurations.Abstractions;
using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Common;
using ShardingCore.DIExtensions;
using ShardingCore.Exceptions;
using ShardingCore.Extensions;
using ShardingCore.Sharding;
using ShardingCore.Sharding.Abstractions;
using ShardingCore.Sharding.ReadWriteConfigurations;
using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions;
using ShardingCore.Sharding.ShardingComparision.Abstractions;
namespace ShardingCore.Core.ShardingConfigurations.ConfigBuilders
{
public class ShardingConfigBuilder<TShardingDbContext> where TShardingDbContext:DbContext,IShardingDbContext
{
public ShardingCoreConfigBuilder<TShardingDbContext> ShardingCoreConfigBuilder { get; }
public ShardingConfigBuilder(ShardingCoreConfigBuilder<TShardingDbContext> shardingCoreConfigBuilder)
{
ShardingCoreConfigBuilder = shardingCoreConfigBuilder;
}
/// <summary>
/// 添加一个分片配置 必填<code>ConfigId</code>和<code>AddDefaultDataSource(string dataSourceName, string connectionString)</code>
/// 如果全局未配置 必须配置<code>UseShardingQuery</code>和<code>UseShardingQuery</code>
/// </summary>
/// <param name="shardingGlobalConfigOptionsConfigure"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ShardingCoreConfigException"></exception>
/// <exception cref="ArgumentException"></exception>
public ShardingConfigBuilder<TShardingDbContext> AddConfig(Action<ShardingConfigOptions> shardingGlobalConfigOptionsConfigure)
{
var shardingGlobalConfigOptions = new ShardingConfigOptions();
shardingGlobalConfigOptionsConfigure?.Invoke(shardingGlobalConfigOptions);
if (string.IsNullOrWhiteSpace(shardingGlobalConfigOptions.ConfigId))
throw new ArgumentNullException(nameof(shardingGlobalConfigOptions.ConfigId));
if (string.IsNullOrWhiteSpace(shardingGlobalConfigOptions.DefaultDataSourceName))
throw new ArgumentNullException(
$"{nameof(shardingGlobalConfigOptions.DefaultDataSourceName)} plz call {nameof(ShardingConfigOptions.AddDefaultDataSource)}");
if (string.IsNullOrWhiteSpace(shardingGlobalConfigOptions.DefaultConnectionString))
throw new ArgumentNullException(
$"{nameof(shardingGlobalConfigOptions.DefaultConnectionString)} plz call {nameof(ShardingConfigOptions.AddDefaultDataSource)}");
if (shardingGlobalConfigOptions.ConnectionStringConfigure is null&& ShardingCoreConfigBuilder.ShardingEntityConfigOptions.ConnectionStringConfigure is null)
throw new ArgumentNullException($"plz call {nameof(shardingGlobalConfigOptions.UseShardingQuery)}");
if (shardingGlobalConfigOptions.ConnectionConfigure is null && ShardingCoreConfigBuilder.ShardingEntityConfigOptions.ConnectionConfigure is null)
throw new ArgumentNullException(
$"plz call {nameof(shardingGlobalConfigOptions.UseShardingTransaction)}");
if (shardingGlobalConfigOptions.ReplaceShardingComparerFactory == null)
{
throw new ShardingCoreConfigException($"{nameof(shardingGlobalConfigOptions.ReplaceShardingComparerFactory)} is null");
}
if (shardingGlobalConfigOptions.MaxQueryConnectionsLimit <= 0)
throw new ArgumentException(
$"{nameof(shardingGlobalConfigOptions.MaxQueryConnectionsLimit)} should greater than and equal 1");
ShardingCoreConfigBuilder.ShardingConfigOptions.Add(shardingGlobalConfigOptions);
return this;
}
/// <summary>
/// 单配置确认
/// </summary>
/// <param name="configurationStrategy"></param>
/// <returns></returns>
public IServiceCollection EnsureConfig(ShardingConfigurationStrategyEnum configurationStrategy = ShardingConfigurationStrategyEnum.ThrowIfNull)
{
return DoEnsureConfig(false,false, configurationStrategy);
}
/// <summary>
/// 单配置确认 自动初始化不需要在手动<code>IShardingBootstrapper.Start()</code>
/// </summary>
/// <param name="configurationStrategy"></param>
/// <returns></returns>
public IServiceCollection EnsureConfigWithAutoStart(ShardingConfigurationStrategyEnum configurationStrategy = ShardingConfigurationStrategyEnum.ThrowIfNull)
{
return DoEnsureConfig(false,true, configurationStrategy);
}
/// <summary>
/// 多配置确认
/// </summary>
/// <param name="configurationStrategy"></param>
/// <returns></returns>
public IServiceCollection EnsureMultiConfig(ShardingConfigurationStrategyEnum configurationStrategy= ShardingConfigurationStrategyEnum.ThrowIfNull)
{
return DoEnsureConfig(true,false, configurationStrategy);
}
/// <summary>
/// 多配置确认 自动初始化不需要在手动<code>IShardingBootstrapper.Start()</code>
/// </summary>
/// <param name="configurationStrategy"></param>
/// <returns></returns>
public IServiceCollection EnsureMultiConfigWithAutoStart(ShardingConfigurationStrategyEnum configurationStrategy= ShardingConfigurationStrategyEnum.ThrowIfNull)
{
return DoEnsureConfig(true,true, configurationStrategy);
}
private IServiceCollection DoEnsureConfig(bool isMultiConfig,
bool autoStart,
ShardingConfigurationStrategyEnum configurationStrategy)
{
if (ShardingCoreConfigBuilder.ShardingConfigOptions.IsEmpty())
throw new ArgumentException($"plz call {nameof(AddConfig)} at least once ");
if (!isMultiConfig)
{
if (ShardingCoreConfigBuilder.ShardingConfigOptions.Count > 1)
{
throw new ArgumentException($"plz call {nameof(AddConfig)} at most once ");
}
}
var services = ShardingCoreConfigBuilder.Services;
services.AddSingleton<IDbContextTypeCollector>(sp => new DbContextTypeCollector<TShardingDbContext>());
services.AddSingleton<IShardingEntityConfigOptions>(sp => ShardingCoreConfigBuilder.ShardingEntityConfigOptions);
services.AddSingleton(sp => ShardingCoreConfigBuilder.ShardingEntityConfigOptions);
services.AddSingleton(sp => CreateShardingConfigurationOptions(isMultiConfig, configurationStrategy));
services.AddSingleton<IShardingReadWriteAccessor, ShardingReadWriteAccessor<TShardingDbContext>>();
if (autoStart)
{
}
services.AddInternalShardingCore<TShardingDbContext>();
return services;
}
private IShardingConfigurationOptions CreateShardingConfigurationOptions(bool isMultiConfig,
ShardingConfigurationStrategyEnum configurationStrategy)
{
IShardingConfigurationOptions shardingConfigurationOptions;
if (!isMultiConfig)
{
shardingConfigurationOptions = new ShardingSingleConfigurationOptions
{
ShardingConfigurationStrategy = configurationStrategy
};
}
else
{
shardingConfigurationOptions = new ShardingMultiConfigurationOptions
{
ShardingConfigurationStrategy = configurationStrategy
};
}
foreach (var configOptions in ShardingCoreConfigBuilder
.ShardingConfigOptions)
{
shardingConfigurationOptions.AddShardingGlobalConfigOptions(configOptions);
}
return shardingConfigurationOptions;
}
}
}
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// using System.Threading.Tasks;
// using Microsoft.EntityFrameworkCore;
// using Microsoft.Extensions.DependencyInjection;
// using Microsoft.Extensions.DependencyInjection.Extensions;
// using ShardingCore.Core.ShardingConfigurations.Abstractions;
// using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Common;
// using ShardingCore.DIExtensions;
// using ShardingCore.Exceptions;
// using ShardingCore.Extensions;
// using ShardingCore.Sharding;
// using ShardingCore.Sharding.Abstractions;
// using ShardingCore.Sharding.ReadWriteConfigurations;
// using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions;
// using ShardingCore.Sharding.ShardingComparision.Abstractions;
//
// namespace ShardingCore.Core.ShardingConfigurations.ConfigBuilders
// {
// public class ShardingConfigBuilder<TShardingDbContext> where TShardingDbContext:DbContext,IShardingDbContext
// {
// public ShardingCoreConfigBuilder<TShardingDbContext> ShardingCoreConfigBuilder { get; }
//
// public ShardingConfigBuilder(ShardingCoreConfigBuilder<TShardingDbContext> shardingCoreConfigBuilder)
// {
// ShardingCoreConfigBuilder = shardingCoreConfigBuilder;
// }
// /// <summary>
// /// 添加一个分片配置 必填<code>ConfigId</code>和<code>AddDefaultDataSource(string dataSourceName, string connectionString)</code>
// /// 如果全局未配置 必须配置<code>UseShardingQuery</code>和<code>UseShardingQuery</code>
// /// </summary>
// /// <param name="shardingGlobalConfigOptionsConfigure"></param>
// /// <returns></returns>
// /// <exception cref="ArgumentNullException"></exception>
// /// <exception cref="ShardingCoreConfigException"></exception>
// /// <exception cref="ArgumentException"></exception>
// public ShardingConfigBuilder<TShardingDbContext> AddConfig(Action<ShardingConfigOptions> shardingGlobalConfigOptionsConfigure)
// {
// var shardingGlobalConfigOptions = new ShardingConfigOptions();
// shardingGlobalConfigOptionsConfigure?.Invoke(shardingGlobalConfigOptions);
// if (string.IsNullOrWhiteSpace(shardingGlobalConfigOptions.ConfigId))
// throw new ArgumentNullException(nameof(shardingGlobalConfigOptions.ConfigId));
// if (string.IsNullOrWhiteSpace(shardingGlobalConfigOptions.DefaultDataSourceName))
// throw new ArgumentNullException(
// $"{nameof(shardingGlobalConfigOptions.DefaultDataSourceName)} plz call {nameof(ShardingConfigOptions.AddDefaultDataSource)}");
//
// if (string.IsNullOrWhiteSpace(shardingGlobalConfigOptions.DefaultConnectionString))
// throw new ArgumentNullException(
// $"{nameof(shardingGlobalConfigOptions.DefaultConnectionString)} plz call {nameof(ShardingConfigOptions.AddDefaultDataSource)}");
//
// if (shardingGlobalConfigOptions.ConnectionStringConfigure is null&& ShardingCoreConfigBuilder.ShardingRouteConfigOptions.ConnectionStringConfigure is null)
// throw new ArgumentNullException($"plz call {nameof(shardingGlobalConfigOptions.UseShardingQuery)}");
// if (shardingGlobalConfigOptions.ConnectionConfigure is null && ShardingCoreConfigBuilder.ShardingRouteConfigOptions.ConnectionConfigure is null)
// throw new ArgumentNullException(
// $"plz call {nameof(shardingGlobalConfigOptions.UseShardingTransaction)}");
//
// if (shardingGlobalConfigOptions.MaxQueryConnectionsLimit <= 0)
// throw new ArgumentException(
// $"{nameof(shardingGlobalConfigOptions.MaxQueryConnectionsLimit)} should greater than and equal 1");
// ShardingCoreConfigBuilder.ShardingConfigOptions.Add(shardingGlobalConfigOptions);
// return this;
// }
// /// <summary>
// /// 单配置确认
// /// </summary>
// /// <param name="configurationStrategy"></param>
// /// <returns></returns>
// public IServiceCollection EnsureConfig(ShardingConfigurationStrategyEnum configurationStrategy = ShardingConfigurationStrategyEnum.ThrowIfNull)
// {
// return DoEnsureConfig(false,false, configurationStrategy);
// }
// /// <summary>
// /// 单配置确认 自动初始化不需要在手动<code>IShardingBootstrapper.Start()</code>
// /// </summary>
// /// <param name="configurationStrategy"></param>
// /// <returns></returns>
// public IServiceCollection EnsureConfigWithAutoStart(ShardingConfigurationStrategyEnum configurationStrategy = ShardingConfigurationStrategyEnum.ThrowIfNull)
// {
// return DoEnsureConfig(false,true, configurationStrategy);
// }
// /// <summary>
// /// 多配置确认
// /// </summary>
// /// <param name="configurationStrategy"></param>
// /// <returns></returns>
// public IServiceCollection EnsureMultiConfig(ShardingConfigurationStrategyEnum configurationStrategy= ShardingConfigurationStrategyEnum.ThrowIfNull)
// {
// return DoEnsureConfig(true,false, configurationStrategy);
// }
// /// <summary>
// /// 多配置确认 自动初始化不需要在手动<code>IShardingBootstrapper.Start()</code>
// /// </summary>
// /// <param name="configurationStrategy"></param>
// /// <returns></returns>
// public IServiceCollection EnsureMultiConfigWithAutoStart(ShardingConfigurationStrategyEnum configurationStrategy= ShardingConfigurationStrategyEnum.ThrowIfNull)
// {
// return DoEnsureConfig(true,true, configurationStrategy);
// }
//
// private IServiceCollection DoEnsureConfig(bool isMultiConfig,
// bool autoStart,
// ShardingConfigurationStrategyEnum configurationStrategy)
// {
// if (ShardingCoreConfigBuilder.ShardingConfigOptions.IsEmpty())
// throw new ArgumentException($"plz call {nameof(AddConfig)} at least once ");
// if (!isMultiConfig)
// {
// if (ShardingCoreConfigBuilder.ShardingConfigOptions.Count > 1)
// {
// throw new ArgumentException($"plz call {nameof(AddConfig)} at most once ");
// }
// }
//
// var services = ShardingCoreConfigBuilder.Services;
// services.AddSingleton<IDbContextTypeCollector>(sp => new DbContextTypeCollector<TShardingDbContext>());
// services.AddSingleton<IShardingRouteConfigOptions>(sp => ShardingCoreConfigBuilder.ShardingRouteConfigOptions);
// services.AddSingleton(sp => ShardingCoreConfigBuilder.ShardingRouteConfigOptions);
//
// services.AddSingleton(sp => CreateShardingConfigurationOptions(isMultiConfig, configurationStrategy));
// services.AddSingleton<IShardingReadWriteAccessor, ShardingReadWriteAccessor<TShardingDbContext>>();
// if (autoStart)
// {
//
// }
//
// services.AddInternalShardingCore<TShardingDbContext>();
// return services;
// }
//
// private IShardingConfigurationOptions CreateShardingConfigurationOptions(bool isMultiConfig,
// ShardingConfigurationStrategyEnum configurationStrategy)
// {
// IShardingConfigurationOptions shardingConfigurationOptions;
// if (!isMultiConfig)
// {
// shardingConfigurationOptions = new ShardingSingleConfigurationOptions
// {
// ShardingConfigurationStrategy = configurationStrategy
// };
// }
// else
// {
// shardingConfigurationOptions = new ShardingMultiConfigurationOptions
// {
// ShardingConfigurationStrategy = configurationStrategy
// };
// }
//
// foreach (var configOptions in ShardingCoreConfigBuilder
// .ShardingConfigOptions)
// {
// shardingConfigurationOptions.AddShardingGlobalConfigOptions(configOptions);
// }
//
// return shardingConfigurationOptions;
// }
// }
// }

View File

@ -1,132 +1,132 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ShardingCore.Core;
using ShardingCore.Core.ShardingConfigurations;
using ShardingCore.Core.ShardingConfigurations.ConfigBuilders;
using ShardingCore.Core.VirtualDatabase.VirtualDataSources;
using ShardingCore.Exceptions;
using ShardingCore.Sharding.Abstractions;
using ShardingCore.Sharding.ParallelTables;
namespace ShardingCore.DIExtensions
{
/*
* @Author: xjm
* @Description:
* @Date: 2021/9/19 20:49:03
* @Ver: 1.0
* @Email: 326308290@qq.com
*/
public class ShardingCoreConfigBuilder<TShardingDbContext> where TShardingDbContext:DbContext,IShardingDbContext
{
public IServiceCollection Services { get; }
public List<ShardingConfigOptions> ShardingConfigOptions { get; }
public ShardingEntityConfigOptions ShardingEntityConfigOptions { get; }
public ShardingCoreConfigBuilder(IServiceCollection services)
{
Services = services;
ShardingConfigOptions = new List<ShardingConfigOptions>();
ShardingEntityConfigOptions = new ShardingEntityConfigOptions();
}
public ShardingConfigBuilder<TShardingDbContext> AddEntityConfig(Action<ShardingEntityConfigOptions> entityConfigure)
{
entityConfigure?.Invoke(ShardingEntityConfigOptions);
return new ShardingConfigBuilder<TShardingDbContext>(this);
}
//public ShardingCoreConfigBuilder<TShardingDbContext, TActualDbContext> AddDefaultDataSource(string dataSourceName, string connectionString)
//{
// if (!string.IsNullOrWhiteSpace(defaultDataSourceName) || !string.IsNullOrWhiteSpace(defaultConnectionString))
// throw new ShardingCoreInvalidOperationException($"{nameof(AddDefaultDataSource)}-{dataSourceName}");
// this.defaultDataSourceName = dataSourceName;
// this.defaultConnectionString = connectionString;
// return this;
//}
//public ShardingCoreConfigBuilder<TShardingDbContext, TActualDbContext> AddDataSource(string dataSourceName, string connectionString)
//{
// if (_dataSources.ContainsKey(dataSourceName))
// throw new ShardingCoreInvalidOperationException($"{nameof(AddDataSource)}-{dataSourceName} repeat");
// _dataSources.Add(dataSourceName, connectionString);
// return this;
//}
}
public class ShardingCoreBeginOptions
{
/// <summary>
/// 配置id
/// </summary>
public string ConfigId { get; set; }
/// <summary>
/// 优先级
/// </summary>
public int Priority { get; set; }
/// <summary>
/// 如果数据库不存在就创建并且创建表除了分表的
/// </summary>
public bool EnsureCreatedWithOutShardingTable { get; set; }
/// <summary>
/// 是否需要在启动时创建分表
/// </summary>
public bool? CreateShardingTableOnStart { get; set; }
///// <summary>
///// 是否自动追踪实体
///// 譬如本次查询涉及到a1,a2,a3这三张表会创建3个dbcontext进行查询如果AutoTrackEntity=false那么针对被创建的dbcontext不会有任何变化还是以追踪的形式查询
///// 因为会同时创建3个dbcontext所以针对跨表查询完成后dbcontext会被回收但是查询还是按原先的行为查询所以如果不启用建议在查询的时候使用notracking
///// 如果AutoTrackEntity=true那么被创建的三个dbcontext还是以原先的表现行为进行查询在查询完成后会再次各自创建对应的dbcontext进行对象的追踪
///// </summary>
//public bool AutoTrackEntity { get; set; }
/// <summary>
/// 当查询遇到没有路由被命中时是否抛出错误
/// </summary>
public bool ThrowIfQueryRouteNotMatch { get; set; } = true;
/// <summary>
/// 忽略建表时的错误
/// </summary>
public bool? IgnoreCreateTableError { get; set; } = true;
public int MaxQueryConnectionsLimit { get; set; } = Environment.ProcessorCount;
public ConnectionModeEnum ConnectionMode { get; set; } = ConnectionModeEnum.SYSTEM_AUTO;
public bool? EnableTableRouteCompileCache { get; set; }
public bool? EnableDataSourceRouteCompileCache { get; set; }
private readonly ISet<Type> _createTableEntities = new HashSet<Type>();
public void AddEntitiesTryCreateTable(params Type[] entityTypes)
{
foreach (var entityType in entityTypes)
{
_createTableEntities.Add(entityType);
}
}
public ISet<Type> GetCreateTableEntities()
{
return _createTableEntities;
}
public readonly ISet<ParallelTableGroupNode> _parallelTables = new HashSet<ParallelTableGroupNode>();
public bool AddParallelTables(params Type[] types)
{
if (types.Length <= 0)
throw new ShardingCoreInvalidOperationException(
$"{nameof(AddParallelTables)} args :[{string.Join(",", types.Select(o => o.Name))}] should more than one length");
return _parallelTables.Add(new ParallelTableGroupNode(types.Select(o => new ParallelTableComparerType(o))));
}
public ISet<ParallelTableGroupNode> GetParallelTableGroupNodes()
{
return _parallelTables;
}
}
}
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using Microsoft.EntityFrameworkCore;
// using Microsoft.Extensions.DependencyInjection;
// using ShardingCore.Core;
// using ShardingCore.Core.ShardingConfigurations;
// using ShardingCore.Core.ShardingConfigurations.ConfigBuilders;
// using ShardingCore.Core.VirtualDatabase.VirtualDataSources;
// using ShardingCore.Exceptions;
// using ShardingCore.Sharding.Abstractions;
// using ShardingCore.Sharding.ParallelTables;
//
// namespace ShardingCore.DIExtensions
// {
// /*
// * @Author: xjm
// * @Description:
// * @Date: 2021/9/19 20:49:03
// * @Ver: 1.0
// * @Email: 326308290@qq.com
// */
// public class ShardingCoreConfigBuilder<TShardingDbContext> where TShardingDbContext:DbContext,IShardingDbContext
// {
// public IServiceCollection Services { get; }
//
//
// public List<ShardingConfigOptions> ShardingConfigOptions { get; }
// public ShardingRouteConfigOptions ShardingRouteConfigOptions { get; }
//
//
// public ShardingCoreConfigBuilder(IServiceCollection services)
// {
// Services = services;
// ShardingConfigOptions = new List<ShardingConfigOptions>();
// ShardingRouteConfigOptions = new ShardingRouteConfigOptions();
// }
//
// public ShardingConfigBuilder<TShardingDbContext> AddEntityConfig(Action<ShardingRouteConfigOptions> entityConfigure)
// {
// entityConfigure?.Invoke(ShardingRouteConfigOptions);
// return new ShardingConfigBuilder<TShardingDbContext>(this);
// }
// //public ShardingCoreConfigBuilder<TShardingDbContext, TActualDbContext> AddDefaultDataSource(string dataSourceName, string connectionString)
// //{
// // if (!string.IsNullOrWhiteSpace(defaultDataSourceName) || !string.IsNullOrWhiteSpace(defaultConnectionString))
// // throw new ShardingCoreInvalidOperationException($"{nameof(AddDefaultDataSource)}-{dataSourceName}");
// // this.defaultDataSourceName = dataSourceName;
// // this.defaultConnectionString = connectionString;
// // return this;
// //}
//
// //public ShardingCoreConfigBuilder<TShardingDbContext, TActualDbContext> AddDataSource(string dataSourceName, string connectionString)
// //{
// // if (_dataSources.ContainsKey(dataSourceName))
// // throw new ShardingCoreInvalidOperationException($"{nameof(AddDataSource)}-{dataSourceName} repeat");
// // _dataSources.Add(dataSourceName, connectionString);
// // return this;
// //}
// }
//
// public class ShardingCoreBeginOptions
// {
// /// <summary>
// /// 配置id
// /// </summary>
// public string ConfigId { get; set; }
// /// <summary>
// /// 优先级
// /// </summary>
// public int Priority { get; set; }
// /// <summary>
// /// 如果数据库不存在就创建并且创建表除了分表的
// /// </summary>
// public bool EnsureCreatedWithOutShardingTable { get; set; }
//
// /// <summary>
// /// 是否需要在启动时创建分表
// /// </summary>
// public bool? CreateShardingTableOnStart { get; set; }
// ///// <summary>
// ///// 是否自动追踪实体
// ///// 譬如本次查询涉及到a1,a2,a3这三张表会创建3个dbcontext进行查询如果AutoTrackEntity=false那么针对被创建的dbcontext不会有任何变化还是以追踪的形式查询
// ///// 因为会同时创建3个dbcontext所以针对跨表查询完成后dbcontext会被回收但是查询还是按原先的行为查询所以如果不启用建议在查询的时候使用notracking
// ///// 如果AutoTrackEntity=true那么被创建的三个dbcontext还是以原先的表现行为进行查询在查询完成后会再次各自创建对应的dbcontext进行对象的追踪
// ///// </summary>
// //public bool AutoTrackEntity { get; set; }
// /// <summary>
// /// 当查询遇到没有路由被命中时是否抛出错误
// /// </summary>
// public bool ThrowIfQueryRouteNotMatch { get; set; } = true;
//
// /// <summary>
// /// 忽略建表时的错误
// /// </summary>
// public bool? IgnoreCreateTableError { get; set; } = true;
// public int MaxQueryConnectionsLimit { get; set; } = Environment.ProcessorCount;
// public ConnectionModeEnum ConnectionMode { get; set; } = ConnectionModeEnum.SYSTEM_AUTO;
// public bool? EnableTableRouteCompileCache { get; set; }
// public bool? EnableDataSourceRouteCompileCache { get; set; }
//
// private readonly ISet<Type> _createTableEntities = new HashSet<Type>();
//
// public void AddEntitiesTryCreateTable(params Type[] entityTypes)
// {
// foreach (var entityType in entityTypes)
// {
// _createTableEntities.Add(entityType);
// }
//
// }
//
// public ISet<Type> GetCreateTableEntities()
// {
// return _createTableEntities;
// }
//
// public readonly ISet<ParallelTableGroupNode> _parallelTables = new HashSet<ParallelTableGroupNode>();
//
// public bool AddParallelTables(params Type[] types)
// {
// if (types.Length <= 0)
// throw new ShardingCoreInvalidOperationException(
// $"{nameof(AddParallelTables)} args :[{string.Join(",", types.Select(o => o.Name))}] should more than one length");
// return _parallelTables.Add(new ParallelTableGroupNode(types.Select(o => new ParallelTableComparerType(o))));
// }
// public ISet<ParallelTableGroupNode> GetParallelTableGroupNodes()
// {
// return _parallelTables;
// }
// }
// }

View File

@ -1,7 +1,5 @@
using Microsoft.EntityFrameworkCore;
using ShardingCore.Sharding.ReadWriteConfigurations;
using ShardingCore.Sharding.ShardingComparision;
using ShardingCore.Sharding.ShardingComparision.Abstractions;
using System;
using System.Collections.Generic;
using System.Data.Common;
@ -10,14 +8,6 @@ namespace ShardingCore.Core.ShardingConfigurations
{
public class ShardingConfigOptions
{
/// <summary>
/// 配置id,如果是单配置可以用guid代替,如果是多配置该属性表示每个配置的id
/// </summary>
public string ConfigId { get; set; }
/// <summary>
/// 优先级多个配置之间的优先级
/// </summary>
public int Priority { get; set; }
/// <summary>
/// 全局配置最大的查询连接数限制,默认系统逻辑处理器<code>Environment.ProcessorCount</code>
/// </summary>
@ -49,13 +39,13 @@ namespace ShardingCore.Core.ShardingConfigurations
DefaultDataSourceName= dataSourceName?? throw new ArgumentNullException(nameof(dataSourceName));
DefaultConnectionString = connectionString ?? throw new ArgumentNullException(nameof(connectionString));
}
public Func<IServiceProvider, IDictionary<string, string>> DataSourcesConfigure { get; private set; }
public Func<IShardingProvider, IDictionary<string, string>> DataSourcesConfigure { get; private set; }
/// <summary>
/// 添加额外数据源
/// </summary>
/// <param name="extraDataSourceConfigure"></param>
/// <exception cref="ArgumentNullException"></exception>
public void AddExtraDataSource(Func<IServiceProvider, IDictionary<string, string>> extraDataSourceConfigure)
public void AddExtraDataSource(Func<IShardingProvider, IDictionary<string, string>> extraDataSourceConfigure)
{
DataSourcesConfigure= extraDataSourceConfigure ?? throw new ArgumentNullException(nameof(extraDataSourceConfigure));
}
@ -69,7 +59,7 @@ namespace ShardingCore.Core.ShardingConfigurations
/// <param name="readConnStringGetStrategy">LatestFirstTime:DbContext缓存,LatestEveryTime:每次都是最新</param>
/// <exception cref="ArgumentNullException"></exception>
public void AddReadWriteSeparation(
Func<IServiceProvider, IDictionary<string, IEnumerable<string>>> readWriteSeparationConfigure,
Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> readWriteSeparationConfigure,
ReadStrategyEnum readStrategyEnum,
bool defaultEnable = false,
int defaultPriority = 10,
@ -83,7 +73,7 @@ namespace ShardingCore.Core.ShardingConfigurations
ShardingReadWriteSeparationOptions.ReadConnStringGetStrategy= readConnStringGetStrategy;
}
public void AddReadWriteNodeSeparation(
Func<IServiceProvider, IDictionary<string, IEnumerable<ReadNode>>> readWriteNodeSeparationConfigure,
Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> readWriteNodeSeparationConfigure,
ReadStrategyEnum readStrategyEnum,
bool defaultEnable = false,
int defaultPriority = 10,
@ -150,16 +140,6 @@ namespace ShardingCore.Core.ShardingConfigurations
{
ShellDbContextConfigure = shellDbContextConfigure ?? throw new ArgumentNullException(nameof(shellDbContextConfigure));
}
public Func<IServiceProvider, IShardingComparer> ReplaceShardingComparerFactory { get; private set; } = sp => new CSharpLanguageShardingComparer();
/// <summary>
/// 替换默认的比较器
/// </summary>
/// <param name="newShardingComparerFactory"></param>
/// <exception cref="ArgumentNullException"></exception>
public void ReplaceShardingComparer(Func<IServiceProvider, IShardingComparer> newShardingComparerFactory)
{
ReplaceShardingComparerFactory = newShardingComparerFactory ?? throw new ArgumentNullException(nameof(newShardingComparerFactory));
}
// public Func<IServiceProvider, ITableEnsureManager<TShardingDbContext>> TableEnsureManagerFactory =
// sp => new EmptyTableEnsureManager<TShardingDbContext>();

View File

@ -1,32 +1,32 @@
using Microsoft.EntityFrameworkCore;
using ShardingCore.Core.ShardingConfigurations.Abstractions;
using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Common;
using ShardingCore.Exceptions;
using ShardingCore.Sharding.Abstractions;
using System.Collections.Generic;
using System.Linq;
namespace ShardingCore.Core.ShardingConfigurations
{
public class ShardingMultiConfigurationOptions : IShardingConfigurationOptions
{
public ShardingConfigurationStrategyEnum ShardingConfigurationStrategy { get; set; } =
ShardingConfigurationStrategyEnum.ThrowIfNull;
private Dictionary<string, ShardingConfigOptions> _shardingGlobalConfigOptions = new ();
public void AddShardingGlobalConfigOptions(ShardingConfigOptions shardingConfigOptions)
{
if (_shardingGlobalConfigOptions.ContainsKey(shardingConfigOptions.ConfigId))
throw new ShardingCoreInvalidOperationException($"repeat add config id:[{shardingConfigOptions.ConfigId}]");
_shardingGlobalConfigOptions.Add(shardingConfigOptions.ConfigId, shardingConfigOptions);
}
public ShardingConfigOptions[] GetAllShardingGlobalConfigOptions()
{
return _shardingGlobalConfigOptions.Values.ToArray();
}
}
}
// using Microsoft.EntityFrameworkCore;
// using ShardingCore.Core.ShardingConfigurations.Abstractions;
// using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Common;
// using ShardingCore.Exceptions;
// using ShardingCore.Sharding.Abstractions;
// using System.Collections.Generic;
// using System.Linq;
//
// namespace ShardingCore.Core.ShardingConfigurations
// {
// public class ShardingMultiConfigurationOptions : IShardingConfigurationOptions
// {
// public ShardingConfigurationStrategyEnum ShardingConfigurationStrategy { get; set; } =
// ShardingConfigurationStrategyEnum.ThrowIfNull;
//
// private Dictionary<string, ShardingConfigOptions> _shardingGlobalConfigOptions = new ();
//
// public void AddShardingGlobalConfigOptions(ShardingConfigOptions shardingConfigOptions)
// {
// if (_shardingGlobalConfigOptions.ContainsKey(shardingConfigOptions.ConfigId))
// throw new ShardingCoreInvalidOperationException($"repeat add config id:[{shardingConfigOptions.ConfigId}]");
//
// _shardingGlobalConfigOptions.Add(shardingConfigOptions.ConfigId, shardingConfigOptions);
// }
//
// public ShardingConfigOptions[] GetAllShardingGlobalConfigOptions()
// {
// return _shardingGlobalConfigOptions.Values.ToArray();
// }
//
// }
// }

View File

@ -6,8 +6,8 @@ namespace ShardingCore.Core.ShardingConfigurations
{
public class ShardingReadWriteSeparationOptions
{
public Func<IServiceProvider, IDictionary<string, IEnumerable<string>>> ReadWriteSeparationConfigure { get; set; }
public Func<IServiceProvider, IDictionary<string, IEnumerable<ReadNode>>> ReadWriteNodeSeparationConfigure { get; set; }
public Func<IShardingProvider, IDictionary<string, IEnumerable<string>>> ReadWriteSeparationConfigure { get; set; }
public Func<IShardingProvider, IDictionary<string, IEnumerable<ReadNode>>> ReadWriteNodeSeparationConfigure { get; set; }
public ReadStrategyEnum ReadStrategy { get; set; } = ReadStrategyEnum.Loop;
public bool DefaultEnable { get; set; } = false;

View File

@ -15,37 +15,37 @@ using ShardingCore.Sharding.ParallelTables;
namespace ShardingCore.Core.ShardingConfigurations
{
public class ShardingEntityConfigOptions : IShardingEntityConfigOptions
public class ShardingRouteConfigOptions : IShardingRouteConfigOptions
{
private readonly IDictionary<Type, Type> _virtualDataSourceRoutes = new Dictionary<Type, Type>();
private readonly IDictionary<Type, Type> _virtualTableRoutes = new Dictionary<Type, Type>();
private readonly ISet<ParallelTableGroupNode> _parallelTables = new HashSet<ParallelTableGroupNode>();
/// <summary>
/// 如果数据库不存在就创建并且创建表除了分表的
/// </summary>
public bool EnsureCreatedWithOutShardingTable { get; set; }
/// <summary>
/// 是否需要在启动时创建分表
/// </summary>
public bool? CreateShardingTableOnStart { get; set; }
/// <summary>
/// 是否在启动时创建数据库
/// </summary>
public bool? CreateDataBaseOnlyOnStart { get; set; }
/// <summary>
/// 当查询遇到没有路由被命中时是否抛出错误
/// </summary>
public bool ThrowIfQueryRouteNotMatch { get; set; } = true;
///// <summary>
///// 全局启用分表路由表达式缓存,仅缓存单个表达式
///// </summary>
//public bool? EnableTableRouteCompileCache { get; set; }
///// <summary>
///// 全局启用分库路由表达式缓存,仅缓存单个表达式
///// </summary>
//public bool? EnableDataSourceRouteCompileCache { get; set; }
// /// <summary>
// /// 如果数据库不存在就创建并且创建表除了分表的
// /// </summary>
// public bool EnsureCreatedWithOutShardingTable { get; set; }
//
// /// <summary>
// /// 是否需要在启动时创建分表
// /// </summary>
// public bool? CreateShardingTableOnStart { get; set; }
// /// <summary>
// /// 是否在启动时创建数据库
// /// </summary>
// public bool? CreateDataBaseOnlyOnStart { get; set; }
// /// <summary>
// /// 当查询遇到没有路由被命中时是否抛出错误
// /// </summary>
// public bool ThrowIfQueryRouteNotMatch { get; set; } = true;
// ///// <summary>
// ///// 全局启用分表路由表达式缓存,仅缓存单个表达式
// ///// </summary>
// //public bool? EnableTableRouteCompileCache { get; set; }
// ///// <summary>
// ///// 全局启用分库路由表达式缓存,仅缓存单个表达式
// ///// </summary>
// //public bool? EnableDataSourceRouteCompileCache { get; set; }
/// <summary>
/// 忽略建表时的错误
/// </summary>
@ -59,6 +59,9 @@ namespace ShardingCore.Core.ShardingConfigurations
var routeType = typeof(TRoute);
AddShardingDataSourceRoute(routeType);
}
public bool ThrowIfQueryRouteNotMatch { get; set; } = true;
public void AddShardingDataSourceRoute(Type routeType)
{
if (!routeType.IsVirtualDataSourceRoute())
@ -151,48 +154,25 @@ namespace ShardingCore.Core.ShardingConfigurations
{
return _parallelTables;
}
/// <summary>
/// 多个DbContext事务传播委托
/// </summary>
public Action<DbConnection, DbContextOptionsBuilder> ConnectionConfigure { get; private set; }
/// <summary>
/// 初始DbContext的创建委托
/// </summary>
public Action<string, DbContextOptionsBuilder> ConnectionStringConfigure { get; private set; }
/// <summary>
/// 仅内部DbContext生效的配置委托
/// </summary>
public Action<DbContextOptionsBuilder> ExecutorDbContextConfigure { get; private set; }
public Action<DbContextOptionsBuilder> ShellDbContextConfigure { get; private set; }
/// <summary>
/// 如何使用字符串创建DbContext
/// </summary>
public void UseShardingQuery(Action<string, DbContextOptionsBuilder> queryConfigure)
{
ConnectionStringConfigure = queryConfigure ?? throw new ArgumentNullException(nameof(queryConfigure));
}
/// <summary>
/// 如何传递事务到其他DbContext
/// </summary>
public void UseShardingTransaction(Action<DbConnection, DbContextOptionsBuilder> transactionConfigure)
{
ConnectionConfigure = transactionConfigure ?? throw new ArgumentNullException(nameof(transactionConfigure));
}
/// <summary>
/// 仅内部真实DbContext配置的方法
/// </summary>
/// <param name="executorDbContextConfigure"></param>
/// <exception cref="ArgumentNullException"></exception>
public void UseExecutorDbContextConfigure(Action<DbContextOptionsBuilder> executorDbContextConfigure)
{
ExecutorDbContextConfigure = executorDbContextConfigure ?? throw new ArgumentNullException(nameof(executorDbContextConfigure));
}
public void UseShellDbContextConfigure(Action<DbContextOptionsBuilder> shellDbContextConfigure)
{
ShellDbContextConfigure = shellDbContextConfigure ?? throw new ArgumentNullException(nameof(shellDbContextConfigure));
}
// /// <summary>
// /// 仅内部DbContext生效的配置委托
// /// </summary>
// public Action<DbContextOptionsBuilder> ExecutorDbContextConfigure { get; private set; }
// public Action<DbContextOptionsBuilder> ShellDbContextConfigure { get; private set; }
//
// /// <summary>
// /// 仅内部真实DbContext配置的方法
// /// </summary>
// /// <param name="executorDbContextConfigure"></param>
// /// <exception cref="ArgumentNullException"></exception>
// public void UseExecutorDbContextConfigure(Action<DbContextOptionsBuilder> executorDbContextConfigure)
// {
// ExecutorDbContextConfigure = executorDbContextConfigure ?? throw new ArgumentNullException(nameof(executorDbContextConfigure));
// }
//
// public void UseShellDbContextConfigure(Action<DbContextOptionsBuilder> shellDbContextConfigure)
// {
// ShellDbContextConfigure = shellDbContextConfigure ?? throw new ArgumentNullException(nameof(shellDbContextConfigure));
// }
}
}

View File

@ -1,28 +1,28 @@
using Microsoft.EntityFrameworkCore;
using ShardingCore.Core.ShardingConfigurations.Abstractions;
using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Common;
using ShardingCore.Exceptions;
using ShardingCore.Sharding.Abstractions;
namespace ShardingCore.Core.ShardingConfigurations
{
public class ShardingSingleConfigurationOptions : IShardingConfigurationOptions
{
private ShardingConfigOptions _shardingConfigOptions;
public ShardingConfigurationStrategyEnum ShardingConfigurationStrategy { get; set; } =
ShardingConfigurationStrategyEnum.ThrowIfNull;
public void AddShardingGlobalConfigOptions(ShardingConfigOptions shardingConfigOptions)
{
if (_shardingConfigOptions != null)
throw new ShardingCoreInvalidOperationException($"repeat add {nameof(ShardingConfigOptions)}");
_shardingConfigOptions= shardingConfigOptions;
}
public ShardingConfigOptions[] GetAllShardingGlobalConfigOptions()
{
return new[] { _shardingConfigOptions };
}
}
}
// using Microsoft.EntityFrameworkCore;
// using ShardingCore.Core.ShardingConfigurations.Abstractions;
// using ShardingCore.Core.VirtualDatabase.VirtualDataSources.Common;
// using ShardingCore.Exceptions;
// using ShardingCore.Sharding.Abstractions;
//
// namespace ShardingCore.Core.ShardingConfigurations
// {
// public class ShardingSingleConfigurationOptions : IShardingConfigurationOptions
// {
//
// private ShardingConfigOptions _shardingConfigOptions;
// public ShardingConfigurationStrategyEnum ShardingConfigurationStrategy { get; set; } =
// ShardingConfigurationStrategyEnum.ThrowIfNull;
//
// public void AddShardingGlobalConfigOptions(ShardingConfigOptions shardingConfigOptions)
// {
// if (_shardingConfigOptions != null)
// throw new ShardingCoreInvalidOperationException($"repeat add {nameof(ShardingConfigOptions)}");
// _shardingConfigOptions= shardingConfigOptions;
// }
//
// public ShardingConfigOptions[] GetAllShardingGlobalConfigOptions()
// {
// return new[] { _shardingConfigOptions };
// }
// }
// }

View File

@ -0,0 +1,33 @@
using System;
using ShardingCore.Core;
using ShardingCore.Exceptions;
namespace ShardingCore.Core
{
public class ShardingProvider:IShardingProvider
{
private readonly IServiceProvider _internalServiceProvider;
private readonly IServiceProvider _applicationServiceProvider;
public ShardingProvider(IServiceProvider internalServiceProvider,IServiceProvider applicationServiceProvider)
{
_internalServiceProvider = internalServiceProvider;
_applicationServiceProvider = applicationServiceProvider;
}
public object GetService(Type serviceType)
{
var service = _internalServiceProvider?.GetService(serviceType);
if (service == null)
{
service= _applicationServiceProvider?.GetService(serviceType);
}
if (service == null)
{
throw new ShardingCoreInvalidOperationException($"cant unable resolve service:[{serviceType}]");
}
return service;
}
}
}

View File

@ -6,36 +6,39 @@ using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ShardingCore.Bootstrappers;
using ShardingCore.Core.DbContextCreator;
using ShardingCore.Core.EntityMetadatas;
using ShardingCore.Core.QueryRouteManagers.Abstractions;
using ShardingCore.Core.QueryTrackers;
using ShardingCore.Core.ShardingConfigurations.Abstractions;
using ShardingCore.Core.ShardingPage.Abstractions;
using ShardingCore.Core.TrackerManagers;
using ShardingCore.Core.UnionAllMergeShardingProviders.Abstractions;
using ShardingCore.Core.VirtualDatabase.VirtualDataSources;
using ShardingCore.Core.VirtualRoutes.Abstractions;
using ShardingCore.Core.VirtualRoutes.TableRoutes.RouteTails.Abstractions;
using ShardingCore.Exceptions;
using ShardingCore.Extensions;
using ShardingCore.Logger;
using ShardingCore.Sharding.Abstractions;
using ShardingCore.Sharding.MergeEngines.ParallelControl;
using ShardingCore.Sharding.ParallelTables;
using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions;
namespace ShardingCore.Core
{
public sealed class ShardingRuntimeContext
public sealed class ShardingRuntimeContext:IShardingRuntimeContext
{
private bool isInited = false;
private object INIT_LOCK = new object();
private bool isInitModeled = false;
private object INIT_MODEL = new object();
private IServiceCollection _serviceMap = new ServiceCollection();
private IServiceProvider _serviceProvider;
private IServiceProvider _applicationServiceProvider;
private ShardingRuntimeContext()
{
_serviceProvider = _serviceMap.BuildServiceProvider();
}
private static readonly ShardingRuntimeContext _instance = new ShardingRuntimeContext();
public static ShardingRuntimeContext GetInstance() => _instance;
public void AddServiceConfig(Action<IServiceCollection> configure)
{
CheckIfBuild();
@ -45,28 +48,99 @@ namespace ShardingCore.Core
public void Initialize()
{
if (isInited)
{
return;
}
lock (INIT_LOCK)
{
if (isInited)
{
return;
}
_serviceProvider = _serviceMap.BuildServiceProvider();
_serviceProvider.GetRequiredService<IShardingBootstrapper>().Start();
isInited = true;
}
}
public IShardingCompilerExecutor GetShardingCompilerExecutor()
{
return GetRequiredService<IShardingCompilerExecutor>();
}
public IShardingReadWriteManager GetShardingReadWriteManager()
{
return GetRequiredService<IShardingReadWriteManager>();
}
public ITrackerManager GetTrackerManager()
{
return GetRequiredService<ITrackerManager>();
}
public IParallelTableManager GetParallelTableManager()
{
return GetRequiredService<IParallelTableManager>();
}
public IDbContextCreator GetDbContextCreator()
{
return GetRequiredService<IDbContextCreator>();
}
public IEntityMetadataManager GetEntityMetadataManager()
{
return GetRequiredService<IEntityMetadataManager>();
}
public IVirtualDataSource GetVirtualDataSource()
{
return GetRequiredService<IVirtualDataSource>();
}
public ITableRouteManager GetTableRouteManager()
{
return GetRequiredService<ITableRouteManager>();
}
public IRouteTailFactory GetRouteTailFactory()
{
return GetRequiredService<IRouteTailFactory>();
}
public IQueryTracker GetQueryTracker()
{
return GetRequiredService<IQueryTracker>();
}
public IUnionAllMergeManager GetUnionAllMergeManager()
{
return GetRequiredService<IUnionAllMergeManager>();
}
public IShardingPageManager GetShardingPageManager()
{
return GetRequiredService<IShardingPageManager>();
}
public void GetOrCreateShardingRuntimeModel(DbContext dbContext)
{
if (isInitModeled) return;
lock (INIT_MODEL)
{
if(isInitModeled) return;
var entityMetadataManager = GetService<IEntityMetadataManager>();
var entityTypes = dbContext.Model.GetEntityTypes();
foreach (var entityType in entityTypes)
{
entityMetadataManager.TryInitModel(entityType);
}
}
}
public void UseLogfactory(ILoggerFactory loggerFactory)
{
InternalLoggerFactory.DefaultFactory = loggerFactory;
}
public void WithApplicationServiceProvider(IServiceProvider applicationServiceProvider)
public void UseApplicationServiceProvider(IServiceProvider applicationServiceProvider)
{
_applicationServiceProvider = applicationServiceProvider;
}
@ -82,30 +156,6 @@ namespace ShardingCore.Core
throw new InvalidOperationException("sharding runtime not init");
}
/// <summary>
/// 创建一个没有依赖注入的对象,但是对象的构造函数参数是已经可以通过依赖注入获取的
/// </summary>
/// <param name="serviceType"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public object CreateInstance(Type serviceType)
{
var constructors
= serviceType.GetTypeInfo().DeclaredConstructors
.Where(c => !c.IsStatic && c.IsPublic)
.ToArray();
if (constructors.Length != 1)
{
throw new ArgumentException(
$"type :[{serviceType}] found more than one declared constructor ");
}
var @params = constructors[0].GetParameters().Select(x => GetRequiredService(x.ParameterType))
.ToArray();
return Activator.CreateInstance(serviceType, @params);
}
public object GetService(Type serviceType)
{
CheckIfNotBuild();
@ -117,34 +167,31 @@ namespace ShardingCore.Core
CheckIfNotBuild();
return _serviceProvider.GetService<TService>();
}
private object GetRequiredService(Type serviceType)
{
var service = _serviceProvider?.GetService(serviceType);
if (service == null)
{
service= _applicationServiceProvider?.GetService(serviceType);
}
if (service == null)
{
throw new ShardingCoreInvalidOperationException($"cant unable resolve service:[{serviceType}]");
}
return service;
public object GetRequiredService(Type serviceType)
{
CheckIfNotBuild();
return _serviceProvider.GetRequiredService(serviceType);
}
public TService GetRequiredService<TService>()
{
CheckIfNotBuild();
return _serviceProvider.GetRequiredService<TService>();
}
public IShardingRouteManager GetShardingRouteManager()
{
return GetService<IShardingRouteManager>();
return GetRequiredService<IShardingRouteManager>();
}
//
// public IShardingEntityConfigOptions<TShardingDbContext> GetRequiredShardingEntityConfigOption<TShardingDbContext>()
// public IShardingRouteConfigOptions<TShardingDbContext> GetRequiredShardingEntityConfigOption<TShardingDbContext>()
// where TShardingDbContext : DbContext, IShardingDbContext
// {
// return (IShardingEntityConfigOptions<TShardingDbContext>)GetRequiredShardingEntityConfigOption(typeof(TShardingDbContext));
// return (IShardingRouteConfigOptions<TShardingDbContext>)GetRequiredShardingEntityConfigOption(typeof(TShardingDbContext));
// }
// public IShardingEntityConfigOptions GetRequiredShardingEntityConfigOption(Type shardingDbContextType)
// public IShardingRouteConfigOptions GetRequiredShardingEntityConfigOption(Type shardingDbContextType)
// {
// return (IShardingEntityConfigOptions)GetService(typeof(IShardingEntityConfigOptions<>).GetGenericType0(shardingDbContextType));
// return (IShardingRouteConfigOptions)GetService(typeof(IShardingRouteConfigOptions<>).GetGenericType0(shardingDbContextType));
// }
}
}

View File

@ -14,8 +14,6 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions
{
public abstract class AbstractVirtualDataSourceConfigurationParams:IVirtualDataSourceConfigurationParams
{
public abstract string ConfigId { get; }
public abstract int Priority { get; }
public virtual int MaxQueryConnectionsLimit { get; } = Environment.ProcessorCount;
public virtual ConnectionModeEnum ConnectionMode { get; } = ConnectionModeEnum.SYSTEM_AUTO;
public abstract string DefaultDataSourceName { get; }
@ -26,7 +24,6 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions
public virtual bool? ReadWriteDefaultEnable { get; }
public virtual int? ReadWriteDefaultPriority { get; }
public virtual ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; }
public virtual IShardingComparer ShardingComparer { get; } = new CSharpLanguageShardingComparer();
public abstract DbContextOptionsBuilder UseDbContextOptionsBuilder(string connectionString,
DbContextOptionsBuilder dbContextOptionsBuilder);

View File

@ -9,14 +9,6 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions
{
public interface IVirtualDataSourceConfigurationParams
{
/// <summary>
/// 配置id
/// </summary>
string ConfigId { get; }
/// <summary>
/// 优先级
/// </summary>
int Priority { get; }
/// <summary>
/// 不能小于等于0 should greater than or equal zero
/// </summary>
@ -51,10 +43,6 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources.Abstractions
/// </summary>
ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; }
/// <summary>
/// 不能为空 should not null
/// </summary>
IShardingComparer ShardingComparer { get; }
/// <summary>
/// 如何根据connectionString 配置 DbContextOptionsBuilder
/// </summary>
/// <param name="connectionString"></param>

View File

@ -20,14 +20,6 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
public interface IVirtualDataSource
{
/// <summary>
/// 配置id
/// </summary>
string ConfigId { get; }
/// <summary>
/// 当前配置的优先级
/// </summary>
int Priority { get; }
/// <summary>
/// 数据源配置
/// </summary>

View File

@ -17,9 +17,6 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
public class SimpleVirtualDataSourceConfigurationParams: AbstractVirtualDataSourceConfigurationParams
{
private readonly ShardingConfigOptions _options;
private readonly IShardingEntityConfigOptions _shardingEntityConfigOptions;
public override string ConfigId { get; }
public override int Priority { get; }
public override int MaxQueryConnectionsLimit { get; }
public override ConnectionModeEnum ConnectionMode { get; }
public override string DefaultDataSourceName { get; }
@ -30,27 +27,22 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
public override bool? ReadWriteDefaultEnable { get; }
public override int? ReadWriteDefaultPriority { get; }
public override ReadConnStringGetStrategyEnum? ReadConnStringGetStrategy { get; }
public override IShardingComparer ShardingComparer { get; }
public SimpleVirtualDataSourceConfigurationParams(IServiceProvider serviceProvider,ShardingConfigOptions options)
public SimpleVirtualDataSourceConfigurationParams(IShardingProvider shardingProvider,ShardingConfigOptions options)
{
_shardingEntityConfigOptions = serviceProvider.GetService<IShardingEntityConfigOptions>();
_options = options;
ConfigId = options.ConfigId;
Priority = options.Priority;
MaxQueryConnectionsLimit = options.MaxQueryConnectionsLimit;
ConnectionMode = options.ConnectionMode;
DefaultDataSourceName = options.DefaultDataSourceName;
DefaultConnectionString = options.DefaultConnectionString;
ExtraDataSources = options.DataSourcesConfigure?.Invoke(serviceProvider)??new ConcurrentDictionary<string, string>();
ShardingComparer = options.ReplaceShardingComparerFactory?.Invoke(serviceProvider) ??
new CSharpLanguageShardingComparer();
ExtraDataSources = options.DataSourcesConfigure?.Invoke(shardingProvider)??new ConcurrentDictionary<string, string>();
if (options.ShardingReadWriteSeparationOptions != null)
{
if (options.ShardingReadWriteSeparationOptions.ReadWriteNodeSeparationConfigure != null)
{
var readConfig = options.ShardingReadWriteSeparationOptions.ReadWriteNodeSeparationConfigure?.Invoke(serviceProvider);
var readConfig = options.ShardingReadWriteSeparationOptions.ReadWriteNodeSeparationConfigure?.Invoke(shardingProvider);
if (readConfig != null)
{
ReadWriteNodeSeparationConfigs = readConfig.ToDictionary(kv=>kv.Key,kv=>kv.Value.ToArray());
@ -58,7 +50,7 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
}
else
{
var nodeConfig = options.ShardingReadWriteSeparationOptions.ReadWriteSeparationConfigure?.Invoke(serviceProvider);
var nodeConfig = options.ShardingReadWriteSeparationOptions.ReadWriteSeparationConfigure?.Invoke(shardingProvider);
if (nodeConfig != null)
{
ReadWriteNodeSeparationConfigs = nodeConfig.ToDictionary(kv => kv.Key,
@ -75,71 +67,43 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
public override DbContextOptionsBuilder UseDbContextOptionsBuilder(string connectionString,
DbContextOptionsBuilder dbContextOptionsBuilder)
{
if(_options.ConnectionStringConfigure==null&&_shardingEntityConfigOptions.ConnectionStringConfigure==null)
if(_options.ConnectionStringConfigure==null)
{
throw new InvalidOperationException($"unknown {nameof(UseDbContextOptionsBuilder)} by connection string");
}
if (_options.ConnectionStringConfigure != null)
{
_options.ConnectionStringConfigure.Invoke(connectionString, dbContextOptionsBuilder);
}
else
{
_shardingEntityConfigOptions.ConnectionStringConfigure.Invoke(connectionString, dbContextOptionsBuilder);
}
_options.ConnectionStringConfigure.Invoke(connectionString, dbContextOptionsBuilder);
return dbContextOptionsBuilder;
}
public override DbContextOptionsBuilder UseDbContextOptionsBuilder(DbConnection dbConnection,
DbContextOptionsBuilder dbContextOptionsBuilder)
{
if (_options.ConnectionConfigure == null && _shardingEntityConfigOptions.ConnectionConfigure == null)
if (_options.ConnectionConfigure == null )
{
throw new InvalidOperationException($"unknown {nameof(UseDbContextOptionsBuilder)} by connection");
}
if (_options.ConnectionConfigure != null)
{
_options.ConnectionConfigure.Invoke(dbConnection, dbContextOptionsBuilder);
}
else
{
_shardingEntityConfigOptions.ConnectionConfigure.Invoke(dbConnection, dbContextOptionsBuilder);
}
_options.ConnectionConfigure.Invoke(dbConnection, dbContextOptionsBuilder);
return dbContextOptionsBuilder;
}
public override void UseShellDbContextOptionBuilder(DbContextOptionsBuilder dbContextOptionsBuilder)
{
if (_options.ShellDbContextConfigure == null && _shardingEntityConfigOptions.ShellDbContextConfigure == null)
if (_options.ShellDbContextConfigure == null)
{
return;
}
if (_options.ShellDbContextConfigure != null)
{
_options.ShellDbContextConfigure.Invoke(dbContextOptionsBuilder);
}
else
{
_shardingEntityConfigOptions.ShellDbContextConfigure?.Invoke(dbContextOptionsBuilder);
}
_options.ShellDbContextConfigure.Invoke(dbContextOptionsBuilder);
}
public override void UseExecutorDbContextOptionBuilder(DbContextOptionsBuilder dbContextOptionsBuilder)
{
if (_options.ExecutorDbContextConfigure == null && _shardingEntityConfigOptions.ExecutorDbContextConfigure == null)
if (_options.ExecutorDbContextConfigure == null )
{
return;
}
if (_options.ExecutorDbContextConfigure != null)
{
_options.ExecutorDbContextConfigure.Invoke(dbContextOptionsBuilder);
}
else
{
_shardingEntityConfigOptions.ExecutorDbContextConfigure?.Invoke(dbContextOptionsBuilder);
}
_options.ExecutorDbContextConfigure.Invoke(dbContextOptionsBuilder);
}
}
}

View File

@ -37,9 +37,6 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
private readonly IVirtualDataSourceRouteManager _dataSourceRouteManager;
private readonly IPhysicDataSourcePool _physicDataSourcePool;
public string ConfigId => ConfigurationParams.ConfigId;
public int Priority => ConfigurationParams.Priority;
public string DefaultDataSourceName { get; private set; }
public string DefaultConnectionString { get; private set; }
public bool UseReadWriteSeparation { get; }
@ -48,7 +45,6 @@ namespace ShardingCore.Core.VirtualDatabase.VirtualDataSources
{
Check.NotNull(configurationParams, nameof(configurationParams));
Check.NotNull(configurationParams.ExtraDataSources, nameof(configurationParams.ExtraDataSources));
Check.NotNull(configurationParams.ShardingComparer, nameof(configurationParams.ShardingComparer));
if(configurationParams.MaxQueryConnectionsLimit<=0)
throw new ArgumentOutOfRangeException(nameof(configurationParams.MaxQueryConnectionsLimit));
ConfigurationParams = configurationParams;

View File

@ -22,7 +22,7 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions
public abstract class AbstractShardingFilterVirtualDataSourceRoute<TEntity, TKey> : AbstractVirtualDataSourceRoute<TEntity, TKey> where TEntity : class
{
public ShardingRouteContext CurrentShardingRouteContext =>ShardingRuntimeContext.GetInstance().GetShardingRouteManager().Current;
public ShardingRouteContext CurrentShardingRouteContext =>RouteShardingProvider.GetRequiredService<IShardingRouteManager>().Current;
/// <summary>
/// 启用提示路由
/// </summary>

View File

@ -35,7 +35,7 @@
// {
// if (EnableRouteParseCompileCache.HasValue)
// return EnableRouteParseCompileCache.Value;
// return EntityConfigOptions.EnableDataSourceRouteCompileCache.GetValueOrDefault();
// return RouteConfigOptions.EnableDataSourceRouteCompileCache.GetValueOrDefault();
// }
// /// <summary>

View File

@ -5,6 +5,7 @@ using ShardingCore.Sharding.MergeEngines.ParallelControl;
using ShardingCore.Sharding.PaginationConfigurations;
using System.Collections.Generic;
using System.Linq;
using ShardingCore.Extensions;
using ShardingCore.Sharding.EntityQueryConfigurations;
namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions
@ -19,7 +20,7 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions
{
public EntityMetadata EntityMetadata { get; private set; }
private readonly DoOnlyOnce _doOnlyOnce = new DoOnlyOnce();
public IShardingEntityConfigOptions EntityConfigOptions { get; private set; }
// public IShardingRouteConfigOptions RouteConfigOptions { get; private set; }
public new PaginationMetadata PaginationMetadata { get; protected set; }
public bool EnablePagination => PaginationMetadata != null;
@ -27,11 +28,15 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions
//public new EntityQueryMetadata EntityQueryMetadata { get; protected set; }
//public bool EnableEntityQuery => EnableEntityQuery != null;
public void Initialize(EntityMetadata entityMetadata)
public IShardingProvider RouteShardingProvider { get; private set;}
public void Initialize(EntityMetadata entityMetadata,IShardingProvider shardingProvider)
{
if (!_doOnlyOnce.IsUnDo())
throw new ShardingCoreInvalidOperationException("already init");
EntityMetadata = entityMetadata;
// RouteConfigOptions = shardingProvider.GetService<IShardingRouteConfigOptions>();
var paginationConfiguration = CreatePaginationConfiguration();
if (paginationConfiguration != null)
{
@ -39,17 +44,13 @@ namespace ShardingCore.Core.VirtualRoutes.DataSourceRoutes.Abstractions
var paginationBuilder = new PaginationBuilder<TEntity>(PaginationMetadata);
paginationConfiguration.Configure(paginationBuilder);
}
//var entityQueryConfiguration = CreateEntityQueryConfiguration();
//if (entityQueryConfiguration != null)
//{
// EntityQueryMetadata = new EntityQueryMetadata();
// var entityQueryBuilder= new EntityQueryBuilder<TEntity>(EntityQueryMetadata);
// entityQueryConfiguration.Configure(entityQueryBuilder);
//}
EntityConfigOptions =ShardingRuntimeContext.GetInstance().GetRequiredShardingEntityConfigOption(entityMetadata.ShardingDbContextType);
// var entityQueryConfiguration = CreateEntityQueryConfiguration();
// if (entityQueryConfiguration != null)
// {
// EntityQueryMetadata = new EntityQueryMetadata();
// var entityQueryBuilder= new EntityQueryBuilder<TEntity>(EntityQueryMetadata);
// entityQueryConfiguration.Configure(entityQueryBuilder);
// }
}
public virtual IPaginationConfiguration<TEntity> CreatePaginationConfiguration()
{

View File

@ -23,7 +23,7 @@ namespace ShardingCore.Core.VirtualRoutes.TableRoutes.Abstractions
/// <typeparam name="TKey"></typeparam>
public abstract class AbstractShardingFilterVirtualTableRoute<T, TKey> : AbstractVirtualTableRoute<T, TKey> where T : class
{
public ShardingRouteContext CurrentShardingRouteContext =>ShardingRuntimeContext.GetInstance().GetShardingRouteManager().Current;
public ShardingRouteContext CurrentShardingRouteContext =>RouteShardingProvider.GetRequiredService<IShardingRouteManager>().Current;
/// <summary>
/// 启用提示路由
/// </summary>

View File

@ -37,7 +37,7 @@
// {
// if (EnableRouteParseCompileCache.HasValue)
// return EnableRouteParseCompileCache.Value;
// return EntityConfigOptions.EnableTableRouteCompileCache.GetValueOrDefault();
// return RouteConfigOptions.EnableTableRouteCompileCache.GetValueOrDefault();
// }
// /// <summary>
// /// 对表达式进行缓存编译默认永久缓存单个参数表达式且不包含orElse只包含单个AndAlso或者没有AndAlso的,

View File

@ -6,6 +6,7 @@ using ShardingCore.Sharding.PaginationConfigurations;
using System.Collections.Generic;
using System.Linq;
using ShardingCore.Core.VirtualRoutes.DataSourceRoutes.RouteRuleEngine;
using ShardingCore.Extensions;
using ShardingCore.Sharding.EntityQueryConfigurations;
using ShardingCore.Sharding.MergeEngines.Common.Abstractions;
@ -21,16 +22,19 @@ namespace ShardingCore.Core.VirtualRoutes.TableRoutes.Abstractions
{
private readonly DoOnlyOnce _doOnlyOnce = new DoOnlyOnce();
public IShardingEntityConfigOptions EntityConfigOptions { get; private set; }
// public IShardingRouteConfigOptions RouteConfigOptions { get; private set; }
public PaginationMetadata PaginationMetadata { get; private set; }
public EntityQueryMetadata EntityQueryMetadata { get; private set; }
public virtual void Initialize(EntityMetadata entityMetadata)
public IShardingProvider RouteShardingProvider { get; private set;}
public virtual void Initialize(EntityMetadata entityMetadata,IShardingProvider shardingProvider)
{
if (!_doOnlyOnce.IsUnDo())
throw new ShardingCoreInvalidOperationException("already init");
RouteShardingProvider = shardingProvider;
EntityMetadata = entityMetadata;
EntityConfigOptions =ShardingRuntimeContext.GetInstance().GetRequiredShardingEntityConfigOption(entityMetadata.ShardingDbContextType);
// RouteConfigOptions =shardingProvider.GetService<IShardingRouteConfigOptions>();
var paginationConfiguration = CreatePaginationConfiguration();
if (paginationConfiguration!=null)
{

View File

@ -38,6 +38,8 @@ using ShardingCore.Sharding.Parsers;
using ShardingCore.Sharding.Parsers.Abstractions;
using ShardingCore.Sharding.ReadWriteConfigurations;
using ShardingCore.Sharding.ReadWriteConfigurations.Abstractions;
using ShardingCore.Sharding.ShardingComparision;
using ShardingCore.Sharding.ShardingComparision.Abstractions;
using ShardingCore.Sharding.ShardingExecutors;
using ShardingCore.Sharding.ShardingExecutors.NativeTrackQueries;
@ -83,18 +85,15 @@ namespace ShardingCore
public static void UseDefaultSharding<TShardingDbContext>(IServiceProvider serviceProvider,DbContextOptionsBuilder dbContextOptionsBuilder) where TShardingDbContext : DbContext, IShardingDbContext
{
var shardingRuntimeContext = serviceProvider.GetRequiredService<IShardingRuntimeContext>();
shardingRuntimeContext.WithApplicationServiceProvider(serviceProvider);
var virtualDataSource = serviceProvider.GetRequiredService<IVirtualDataSourceManager>().GetCurrentVirtualDataSource();
var virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
var connectionString = virtualDataSource.GetConnectionString(virtualDataSource.DefaultDataSourceName);
var contextOptionsBuilder = virtualDataSource.ConfigurationParams.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder).UseSharding<TShardingDbContext>();
var contextOptionsBuilder = virtualDataSource.ConfigurationParams.UseDbContextOptionsBuilder(connectionString, dbContextOptionsBuilder).UseSharding<TShardingDbContext>(shardingRuntimeContext);
virtualDataSource.ConfigurationParams.UseShellDbContextOptionBuilder(contextOptionsBuilder);
}
internal static IServiceCollection AddInternalShardingCore<TShardingDbContext>(this IServiceCollection services) where TShardingDbContext : DbContext, IShardingDbContext
{
//虚拟数据源管理者
services.TryAddSingleton<IVirtualDataSourceManager, VirtualDataSourceManager>();
services.TryAddSingleton<IVirtualDataSourceAccessor, VirtualDataSourceAccessor>();
services.TryAddSingleton<IVirtualDataSourceConfigurationParams, SimpleVirtualDataSourceConfigurationParams>();
//分表dbcontext创建
services.TryAddSingleton<IDbContextCreator, ActivatorDbContextCreator<TShardingDbContext>>();
@ -104,10 +103,12 @@ namespace ShardingCore
services.TryAddSingleton<IStreamMergeContextFactory<TShardingDbContext>, StreamMergeContextFactory<TShardingDbContext>>();
services.TryAddSingleton<IShardingTableCreator, ShardingTableCreator>();
//虚拟数据源管理
services.TryAddSingleton<IVirtualDataSource, VirtualDataSource>();
services.TryAddSingleton<IVirtualDataSourceRouteManager, VirtualDataSourceRouteManager>();
services.TryAddSingleton<IDataSourceRouteRuleEngine<TShardingDbContext>, DataSourceRouteRuleEngine<TShardingDbContext>>();
services.TryAddSingleton<IDataSourceRouteRuleEngineFactory<TShardingDbContext>, DataSourceRouteRuleEngineFactory<TShardingDbContext>>();
//读写分离链接创建工厂
services.TryAddSingleton<IShardingReadWriteAccessor, ShardingReadWriteAccessor>();
services.TryAddSingleton<IReadWriteConnectorFactory, ReadWriteConnectorFactory>();
//虚拟表管理
@ -124,7 +125,6 @@ namespace ShardingCore
services.TryAddSingleton<IShardingCompilerExecutor, DefaultShardingCompilerExecutor>();
services.TryAddSingleton<IQueryCompilerContextFactory, QueryCompilerContextFactory>();
services.TryAddSingleton<IShardingQueryExecutor, DefaultShardingQueryExecutor>();
services.TryAddSingleton<IReadWriteConnectorFactory, ReadWriteConnectorFactory>();
//
services.TryAddSingleton<IPrepareParser, DefaultPrepareParser>();
@ -147,6 +147,7 @@ namespace ShardingCore
services.TryAddSingleton<INativeTrackQueryExecutor, NativeTrackQueryExecutor>();
//读写分离手动指定
services.TryAddSingleton<IShardingReadWriteManager, ShardingReadWriteManager>();
services.TryAddSingleton<IShardingComparer, CSharpLanguageShardingComparer>();
services.TryAddShardingJob();

View File

@ -26,7 +26,7 @@
// private static readonly ILogger<DataSourceInitializer<TShardingDbContext>> _logger =
// InternalLoggerFactory.CreateLogger<DataSourceInitializer<TShardingDbContext>>();
//
// private readonly IShardingEntityConfigOptions<TShardingDbContext> _entityConfigOptions;
// private readonly IShardingRouteConfigOptions<TShardingDbContext> _routeConfigOptions;
// private readonly IVirtualDataSourceManager<TShardingDbContext> _virtualDataSourceManager;
// private readonly IRouteTailFactory _routeTailFactory;
// private readonly IVirtualTableManager<TShardingDbContext> _virtualTableManager;
@ -34,13 +34,13 @@
// private readonly IShardingTableCreator<TShardingDbContext> _tableCreator;
//
// public DataSourceInitializer(
// IShardingEntityConfigOptions<TShardingDbContext> entityConfigOptions,
// IShardingRouteConfigOptions<TShardingDbContext> routeConfigOptions,
// IVirtualDataSourceManager<TShardingDbContext> virtualDataSourceManager,
// IRouteTailFactory routeTailFactory, IVirtualTableManager<TShardingDbContext> virtualTableManager,
// IEntityMetadataManager<TShardingDbContext> entityMetadataManager,
// IShardingTableCreator<TShardingDbContext> shardingTableCreator)
// {
// _entityConfigOptions = entityConfigOptions;
// _routeConfigOptions = routeConfigOptions;
// _virtualDataSourceManager = virtualDataSourceManager;
// _routeTailFactory = routeTailFactory;
// _virtualTableManager = virtualTableManager;
@ -54,9 +54,9 @@
// {
// // var createDatabase = !needCreateDatabase.HasValue || needCreateDatabase.Value;
// //
// // if ((_entityConfigOptions.EnsureCreatedWithOutShardingTable || !isOnStart)&&createDatabase)
// // if ((_routeConfigOptions.EnsureCreatedWithOutShardingTable || !isOnStart)&&createDatabase)
// // EnsureCreated(virtualDataSource, context, dataSourceName);
// // else if (_entityConfigOptions.CreateDataBaseOnlyOnStart.GetValueOrDefault()&& createDatabase)
// // else if (_routeConfigOptions.CreateDataBaseOnlyOnStart.GetValueOrDefault()&& createDatabase)
// // {
// // EnsureCreateDataBaseOnly(context, dataSourceName);
// // }
@ -131,7 +131,7 @@
// // }
// // }
// //
// // return _entityConfigOptions.CreateShardingTableOnStart.GetValueOrDefault();
// // return _routeConfigOptions.CreateShardingTableOnStart.GetValueOrDefault();
// // }
// //
// // private void EnsureCreated(IVirtualDataSource<TShardingDbContext> virtualDataSource, DbContext context,

View File

@ -1,21 +1,21 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ShardingCore.DIExtensions;
using ShardingCore.Sharding.Abstractions;
namespace ShardingCore.Extensions
{
public static class ShardingCoreConfigBuilderExtension
{
[ExcludeFromCodeCoverage]
public static void AddEntityTryCreateTable<TEntity>(this ShardingCoreBeginOptions source) where TEntity:class
{
source.AddEntitiesTryCreateTable(typeof(TEntity));
}
}
}
// using System;
// using System.Collections.Generic;
// using System.Diagnostics.CodeAnalysis;
// using System.Linq;
// using System.Text;
// using System.Threading.Tasks;
// using Microsoft.EntityFrameworkCore;
// using ShardingCore.DIExtensions;
// using ShardingCore.Sharding.Abstractions;
//
// namespace ShardingCore.Extensions
// {
// public static class ShardingCoreConfigBuilderExtension
// {
// [ExcludeFromCodeCoverage]
// public static void AddEntityTryCreateTable<TEntity>(this ShardingCoreBeginOptions source) where TEntity:class
// {
// source.AddEntitiesTryCreateTable(typeof(TEntity));
// }
// }
// }

View File

@ -5,22 +5,22 @@ namespace ShardingCore.Extensions
{
public static class ShardingEntityConfigOptionExtension
{
public static bool TryGetVirtualTableRoute<TEntity>(this IShardingEntityConfigOptions shardingEntityConfigOptions, out Type virtualTableRouteType) where TEntity:class
public static bool TryGetVirtualTableRoute<TEntity>(this IShardingRouteConfigOptions shardingRouteConfigOptions, out Type virtualTableRouteType) where TEntity:class
{
if (shardingEntityConfigOptions.HasVirtualTableRoute(typeof(TEntity)))
if (shardingRouteConfigOptions.HasVirtualTableRoute(typeof(TEntity)))
{
virtualTableRouteType = shardingEntityConfigOptions.GetVirtualTableRouteType(typeof(TEntity));
virtualTableRouteType = shardingRouteConfigOptions.GetVirtualTableRouteType(typeof(TEntity));
return virtualTableRouteType != null;
}
virtualTableRouteType = null;
return false;
}
public static bool TryGetVirtualDataSourceRoute<TEntity>(this IShardingEntityConfigOptions shardingEntityConfigOptions,out Type virtualDataSourceRouteType) where TEntity:class
public static bool TryGetVirtualDataSourceRoute<TEntity>(this IShardingRouteConfigOptions shardingRouteConfigOptions,out Type virtualDataSourceRouteType) where TEntity:class
{
if (shardingEntityConfigOptions.HasVirtualDataSourceRoute(typeof(TEntity)))
if (shardingRouteConfigOptions.HasVirtualDataSourceRoute(typeof(TEntity)))
{
virtualDataSourceRouteType = shardingEntityConfigOptions.GetVirtualDataSourceRouteType(typeof(TEntity));
virtualDataSourceRouteType = shardingRouteConfigOptions.GetVirtualDataSourceRouteType(typeof(TEntity));
return virtualDataSourceRouteType != null;
}

View File

@ -0,0 +1,57 @@
using System;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using ShardingCore.Core;
namespace ShardingCore.Extensions
{
public static class ShardingProviderExtension
{
/// <summary>
/// 创建一个没有依赖注入的对象,但是对象的构造函数参数是已经可以通过依赖注入获取的
/// </summary>
/// <param name="shardingProvider"></param>
/// <param name="serviceType"></param>
/// <returns></returns>
/// <exception cref="ArgumentException"></exception>
public static object CreateInstance(this IShardingProvider shardingProvider,Type serviceType)
{
var constructors
= serviceType.GetTypeInfo().DeclaredConstructors
.Where(c => !c.IsStatic && c.IsPublic)
.ToArray();
if (constructors.Length != 1)
{
throw new ArgumentException(
$"type :[{serviceType}] found more than one declared constructor ");
}
var @params = constructors[0].GetParameters().Select(x => shardingProvider.GetService(x.ParameterType))
.ToArray();
return Activator.CreateInstance(serviceType, @params);
}
public static object GetRequiredService(this IShardingProvider shardingProvider,Type serviceType)
{
var service = shardingProvider.GetService(serviceType);
if (service == null)
{
throw new ArgumentNullException($"cant resolve {serviceType.FullName}");
}
return service;
}
public static TService GetService<TService>(this IShardingProvider shardingProvider)
{
return (TService)shardingProvider.GetService(typeof(TService));
}
public static TService GetRequiredService<TService>(this IShardingProvider shardingProvider)
{
return (TService)shardingProvider.GetRequiredService(typeof(TService));
}
}
}

View File

@ -42,7 +42,7 @@ namespace ShardingCore.Sharding.Parsers.Visitors
public ShardingQueryPrepareVisitor(IShardingDbContext shardingDbContext)
{
_shardingDbContext = shardingDbContext;
_trackerManager = ((DbContext)shardingDbContext).GetRequireService<IShardingRuntimeContext>()
_trackerManager =shardingDbContext.GetShardingRuntimeContext()
.GetTrackerManager();
}
public ShardingPrepareResult GetShardingPrepareResult()

View File

@ -13,7 +13,6 @@ namespace ShardingCore.Sharding.ReadWriteConfigurations.Abstractions
*/
public interface IShardingReadWriteAccessor
{
Type ShardingDbContextType { get;}
ShardingReadWriteContext ShardingReadWriteContext { get; set; }
}
}

View File

@ -15,11 +15,10 @@ namespace ShardingCore.Sharding.ReadWriteConfigurations
* @Ver: 1.0
* @Email: 326308290@qq.com
*/
public class ShardingReadWriteAccessor<TShardingDbContext>:IShardingReadWriteAccessor where TShardingDbContext:DbContext,IShardingDbContext
public class ShardingReadWriteAccessor:IShardingReadWriteAccessor
{
private static AsyncLocal<ShardingReadWriteContext> _shardingReadWriteContext = new AsyncLocal<ShardingReadWriteContext>();
public Type ShardingDbContextType => typeof(TShardingDbContext);
/// <summary>
///

View File

@ -61,8 +61,7 @@ namespace ShardingCore.Sharding.ShardingDbContextExecutors
//初始化
var shardingRuntimeContext = shardingDbContext.GetRequireService<IShardingRuntimeContext>();
shardingRuntimeContext.GetOrCreateShardingRuntimeModel(shardingDbContext);
var virtualDataSourceManager = shardingRuntimeContext.GetVirtualDataSourceManager();
_virtualDataSource = virtualDataSourceManager.GetCurrentVirtualDataSource();
_virtualDataSource = shardingRuntimeContext.GetVirtualDataSource();
_tableRouteManager = shardingRuntimeContext.GetTableRouteManager();
_dbContextCreator = shardingRuntimeContext.GetDbContextCreator();
_entityMetadataManager = shardingRuntimeContext.GetEntityMetadataManager();

View File

@ -70,7 +70,7 @@ namespace ShardingCore.Sharding
public bool IsCrossTable => MergeQueryCompilerContext.IsCrossTable();
private readonly ITrackerManager _trackerManager;
private readonly IShardingEntityConfigOptions _shardingEntityConfigOptions;
private readonly IShardingRouteConfigOptions _shardingRouteConfigOptions;
private readonly ConcurrentDictionary<DbContext, object> _parallelDbContexts;
@ -84,7 +84,7 @@ namespace ShardingCore.Sharding
public StreamMergeContext(IMergeQueryCompilerContext mergeQueryCompilerContext,IParseResult parseResult,IQueryable rewriteQueryable,IOptimizeResult optimizeResult,
IRouteTailFactory routeTailFactory,ITrackerManager trackerManager,IShardingEntityConfigOptions shardingEntityConfigOptions)
IRouteTailFactory routeTailFactory,ITrackerManager trackerManager,IShardingRouteConfigOptions shardingRouteConfigOptions)
{
MergeQueryCompilerContext = mergeQueryCompilerContext;
ShardingRuntimeContext = ((DbContext)mergeQueryCompilerContext.GetShardingDbContext())
@ -95,7 +95,7 @@ namespace ShardingCore.Sharding
_routeTailFactory = routeTailFactory;
QueryEntities= MergeQueryCompilerContext.GetQueryEntities().Keys.ToHashSet();
_trackerManager =trackerManager;
_shardingEntityConfigOptions = shardingEntityConfigOptions;
_shardingRouteConfigOptions = shardingRouteConfigOptions;
_parallelDbContexts = new ConcurrentDictionary<DbContext, object>();
Orders = parseResult.GetOrderByContext().PropertyOrders.ToArray();
Skip = parseResult.GetPaginationContext().Skip;
@ -265,7 +265,7 @@ namespace ShardingCore.Sharding
public IShardingComparer GetShardingComparer()
{
return GetShardingDbContext().GetVirtualDataSource().ConfigurationParams.ShardingComparer;
return GetShardingDbContext().GetShardingRuntimeContext().GetRequiredService<IShardingComparer>();
}
public TResult PreperExecute<TResult>(Func<TResult> emptyFunc)
@ -296,7 +296,7 @@ namespace ShardingCore.Sharding
private bool ThrowIfQueryRouteNotMatch()
{
return _shardingEntityConfigOptions.ThrowIfQueryRouteNotMatch;
return _shardingRouteConfigOptions.ThrowIfQueryRouteNotMatch;
}
public bool UseUnionAllMerge()

View File

@ -25,25 +25,25 @@ namespace ShardingCore.Sharding
private readonly IQueryableRewriteEngine _queryableRewriteEngine;
private readonly IQueryableOptimizeEngine _queryableOptimizeEngine;
private readonly ITrackerManager _trackerManager;
private readonly IShardingEntityConfigOptions _shardingEntityConfigOptions;
private readonly IShardingRouteConfigOptions _shardingRouteConfigOptions;
public StreamMergeContextFactory(IRouteTailFactory routeTailFactory
, IQueryableParseEngine queryableParseEngine, IQueryableRewriteEngine queryableRewriteEngine, IQueryableOptimizeEngine queryableOptimizeEngine,
ITrackerManager trackerManager,IShardingEntityConfigOptions shardingEntityConfigOptions)
ITrackerManager trackerManager,IShardingRouteConfigOptions shardingRouteConfigOptions)
{
_routeTailFactory = routeTailFactory;
_queryableParseEngine = queryableParseEngine;
_queryableRewriteEngine = queryableRewriteEngine;
_queryableOptimizeEngine = queryableOptimizeEngine;
_trackerManager = trackerManager;
_shardingEntityConfigOptions = shardingEntityConfigOptions;
_shardingRouteConfigOptions = shardingRouteConfigOptions;
}
public StreamMergeContext Create(IMergeQueryCompilerContext mergeQueryCompilerContext)
{
var parseResult = _queryableParseEngine.Parse(mergeQueryCompilerContext);
var rewriteQueryable = _queryableRewriteEngine.GetRewriteQueryable(mergeQueryCompilerContext, parseResult);
var optimizeResult = _queryableOptimizeEngine.Optimize(mergeQueryCompilerContext, parseResult, rewriteQueryable);
return new StreamMergeContext(mergeQueryCompilerContext, parseResult, rewriteQueryable,optimizeResult, _routeTailFactory,_trackerManager,_shardingEntityConfigOptions);
return new StreamMergeContext(mergeQueryCompilerContext, parseResult, rewriteQueryable,optimizeResult, _routeTailFactory,_trackerManager,_shardingRouteConfigOptions);
}
}
}

View File

@ -141,14 +141,14 @@
// //{
// // return (IShardingConfigOption)ServiceProvider.GetService(typeof(IShardingConfigOption<>).GetGenericType0(shardingDbContextType));
// //}
// public static IShardingEntityConfigOptions<TShardingDbContext> GetRequiredShardingEntityConfigOption<TShardingDbContext>()
// public static IShardingRouteConfigOptions<TShardingDbContext> GetRequiredShardingEntityConfigOption<TShardingDbContext>()
// where TShardingDbContext : DbContext, IShardingDbContext
// {
// return (IShardingEntityConfigOptions<TShardingDbContext>)GetRequiredShardingEntityConfigOption(typeof(TShardingDbContext));
// return (IShardingRouteConfigOptions<TShardingDbContext>)GetRequiredShardingEntityConfigOption(typeof(TShardingDbContext));
// }
// public static IShardingEntityConfigOptions GetRequiredShardingEntityConfigOption(Type shardingDbContextType)
// public static IShardingRouteConfigOptions GetRequiredShardingEntityConfigOption(Type shardingDbContextType)
// {
// return (IShardingEntityConfigOptions)ServiceProvider.GetService(typeof(IShardingEntityConfigOptions<>).GetGenericType0(shardingDbContextType));
// return (IShardingRouteConfigOptions)ServiceProvider.GetService(typeof(IShardingRouteConfigOptions<>).GetGenericType0(shardingDbContextType));
// }
//
// public static IVirtualDataSourceManager<TShardingDbContext> GetRequiredVirtualDataSourceManager<TShardingDbContext>()

View File

@ -0,0 +1,81 @@
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ShardingCore.Core;
using ShardingCore.Core.ShardingConfigurations;
using ShardingCore.Core.ShardingConfigurations.Abstractions;
using ShardingCore.Sharding.Abstractions;
namespace ShardingCore
{
public class ShardingRuntimeBuilder<TShardingDbContext> where TShardingDbContext : DbContext, IShardingDbContext
{
private IShardingRouteConfigOptions _shardingRouteConfigOptions = new ShardingRouteConfigOptions();
private ShardingConfigOptions _shardingConfigOptions = new ShardingConfigOptions();
public ShardingRuntimeBuilder()
{
}
public ShardingRuntimeBuilder<TShardingDbContext> UseRouteConfig(Action<IShardingRouteConfigOptions> configure)
{
if (configure == null)
throw new ArgumentNullException($"{nameof(configure)}");
configure.Invoke(_shardingRouteConfigOptions);
return this;
}
public ShardingRuntimeBuilder<TShardingDbContext> UseConfig(Action<ShardingConfigOptions> configure)
{
if (configure == null)
throw new ArgumentNullException($"{nameof(configure)}");
configure.Invoke(_shardingConfigOptions);
if (string.IsNullOrWhiteSpace(_shardingConfigOptions.DefaultDataSourceName))
throw new ArgumentNullException(
$"{nameof(_shardingConfigOptions.DefaultDataSourceName)} plz call {nameof(ShardingConfigOptions.AddDefaultDataSource)}");
if (string.IsNullOrWhiteSpace(_shardingConfigOptions.DefaultConnectionString))
throw new ArgumentNullException(
$"{nameof(_shardingConfigOptions.DefaultConnectionString)} plz call {nameof(ShardingConfigOptions.AddDefaultDataSource)}");
if (_shardingConfigOptions.ConnectionStringConfigure is null)
throw new ArgumentNullException($"plz call {nameof(_shardingConfigOptions.UseShardingQuery)}");
if (_shardingConfigOptions.ConnectionConfigure is null )
throw new ArgumentNullException(
$"plz call {nameof(_shardingConfigOptions.UseShardingTransaction)}");
if (_shardingConfigOptions.MaxQueryConnectionsLimit <= 0)
throw new ArgumentException(
$"{nameof(_shardingConfigOptions.MaxQueryConnectionsLimit)} should greater than and equal 1");
return this;
}
public IShardingRuntimeContext Build()
{
return Build(null);
}
public IShardingRuntimeContext Build(IServiceProvider appServiceProvider)
{
return Build(appServiceProvider, appServiceProvider?.GetService<ILoggerFactory>());
}
public IShardingRuntimeContext Build(IServiceProvider appServiceProvider, ILoggerFactory loggerFactory)
{
var shardingRuntimeContext = new ShardingRuntimeContext();
shardingRuntimeContext.UseApplicationServiceProvider(appServiceProvider);
shardingRuntimeContext.UseLogfactory(loggerFactory);
shardingRuntimeContext.AddServiceConfig(services =>
{
services.AddSingleton<IDbContextTypeCollector>(sp => new DbContextTypeCollector<TShardingDbContext>());
services.AddSingleton<IShardingRouteConfigOptions>(sp => _shardingRouteConfigOptions);
services.AddSingleton(sp => _shardingConfigOptions);
services.AddSingleton<IShardingProvider>(sp => new ShardingProvider(sp,appServiceProvider));
services.AddInternalShardingCore<TShardingDbContext>();
});
shardingRuntimeContext.Initialize();
return shardingRuntimeContext;
}
}
}

View File

@ -26,14 +26,14 @@ namespace ShardingCore.TableCreator
InternalLoggerFactory.CreateLogger<ShardingTableCreator>();
private readonly IServiceProvider _serviceProvider;
private readonly IShardingEntityConfigOptions _entityConfigOptions;
private readonly IShardingRouteConfigOptions _routeConfigOptions;
private readonly IRouteTailFactory _routeTailFactory;
public ShardingTableCreator(IServiceProvider serviceProvider,
IShardingEntityConfigOptions entityConfigOptions, IRouteTailFactory routeTailFactory)
IShardingRouteConfigOptions routeConfigOptions, IRouteTailFactory routeTailFactory)
{
_serviceProvider = serviceProvider;
_entityConfigOptions = entityConfigOptions;
_routeConfigOptions = routeConfigOptions;
_routeTailFactory = routeTailFactory;
}
@ -64,7 +64,7 @@ namespace ShardingCore.TableCreator
}
catch (Exception ex)
{
if (!_entityConfigOptions.IgnoreCreateTableError.GetValueOrDefault())
if (!_routeConfigOptions.IgnoreCreateTableError.GetValueOrDefault())
{
_logger.LogWarning(ex,
$"create table error entity name:[{shardingEntityType.Name}].");