Skip to content

Commit

Permalink
Merge pull request #65 from EasilyNET/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
joesdu authored Apr 9, 2023
2 parents 651c20e + 69a758a commit 1346968
Show file tree
Hide file tree
Showing 15 changed files with 96 additions and 58 deletions.
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<Project>

<PropertyGroup>
<Version>1.3.6.3</Version>
<Version>1.3.7</Version>
<LangVersion>preview</LangVersion>
<RepositoryUrl>https://github.com/EasilyNET/EasilyNET</RepositoryUrl>
<Nullable>enable</Nullable>
Expand Down
4 changes: 3 additions & 1 deletion Test/WebApi.Test.Unit/Controllers/MongoTestController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ public async Task InitTest2()
var date = DateOnly.FromDateTime(DateTime.Now.AddDays(i));
os.Add(new() { Id = Guid.NewGuid().ToString(), Date = date, Index = i });
}
await db.Test2.InsertManyAsync(os);
var session = await db.GetStartedSessionAsync();
await db.Test2.InsertManyAsync(session, os);
await session.CommitTransactionAsync();
}

/// <summary>
Expand Down
10 changes: 5 additions & 5 deletions Test/WebApi.Test.Unit/DbContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ namespace WebApi.Test.Unit;
/// <summary>
/// DBContext
/// </summary>
public class DbContext : EasilyNETMongoContext
public class DbContext : EasilyMongoContext
{
/// <summary>
/// 默认无参构造函数
Expand Down Expand Up @@ -40,21 +40,21 @@ public DbContext(string test, int i1)
/// <summary>
/// MongoTest
/// </summary>
public IMongoCollection<MongoTest> Test => Collection<MongoTest>("mongo.test");
public IMongoCollection<MongoTest> Test => GetCollection<MongoTest>("mongo.test");

/// <summary>
/// MongoTest2
/// </summary>
public IMongoCollection<MongoTest2> Test2 => Collection<MongoTest2>("mongo.test2");
public IMongoCollection<MongoTest2> Test2 => GetCollection<MongoTest2>("mongo.test2");
}

/// <summary>
/// DBContext2
/// </summary>
public class DbContext2 : EasilyNETMongoContext
public class DbContext2 : EasilyMongoContext
{
/// <summary>
/// MongoTest
/// </summary>
public IMongoCollection<MongoTest> Test => Collection<MongoTest>("mongo.test2");
public IMongoCollection<MongoTest> Test => GetCollection<MongoTest>("mongo.test2");
}
4 changes: 4 additions & 0 deletions Test/WebApi.Test.Unit/Program.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
using EasilyNET.AutoDependencyInjection.Extensions;
using EasilyNET.Core.PinYin;
using Serilog;
using Serilog.Events;
using WebApi.Test.Unit;

var builder = WebApplication.CreateBuilder(args);
Console.WriteLine("微软爸爸就是牛逼");
Console.WriteLine(PyTools.GetPinYin("微软爸爸就是牛逼"));
Console.WriteLine(PyTools.GetInitials("微软爸爸就是牛逼"));

//添加Serilog配置
_ = builder.Host.UseSerilog((hbc, lc) =>
Expand Down
6 changes: 3 additions & 3 deletions src/EasilyNET.Core/Misc/DateTimeExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,12 +207,12 @@ public static string DayName(this DayOfWeek day, int type = 1)
/// 验证时间段和另一个时间段的重合情况
/// </summary>
/// <param name="sub">需要验证的时间段</param>
/// <param name="validate">所属源</param>
/// <param name="source">所属源</param>
/// <returns>ETimeOverlap</returns>
public static ETimeOverlap TimeOverlap(Tuple<DateTime, DateTime> sub, Tuple<DateTime, DateTime> validate)
public static ETimeOverlap TimeOverlap(Tuple<DateTime, DateTime> sub, Tuple<DateTime, DateTime> source)
{
var (subStart, subEnd) = sub;
var (validateStart, validateEnd) = validate;
var (validateStart, validateEnd) = source;
return (subStart < validateEnd && validateStart < subEnd) switch
{
true when subStart >= validateStart && subEnd <= validateEnd => ETimeOverlap.完全重合,
Expand Down
4 changes: 2 additions & 2 deletions src/EasilyNET.Core/Misc/DoubleExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static class DoubleExtensions
/// </summary>
/// <param name="number">金额</param>
/// <returns>返回大写形式</returns>
public static string ToRMB(this decimal number)
public static string ToRmb(this decimal number)
{
var s = number.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
#if !NETSTANDARD
Expand All @@ -51,5 +51,5 @@ public static string ToRMB(this decimal number)
/// </summary>
/// <param name="number">金额</param>
/// <returns>返回大写形式</returns>
public static string ToRMB(this double number) => ((decimal)number).ToRMB();
public static string ToRmb(this double number) => ((decimal)number).ToRmb();
}
2 changes: 1 addition & 1 deletion src/EasilyNET.Core/Misc/StringExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ public static string TruncateJson(this string json, Func<string, bool> predicate
/// </summary>
/// <param name="numStr">金额</param>
/// <returns>返回大写形式</returns>
public static string ToRMB(this string numStr) => numStr.ConvertTo<decimal>().ToRMB();
public static string ToRmb(this string numStr) => numStr.ConvertTo<decimal>().ToRmb();

/// <summary>
/// 将格式化日期串转化为相应的日期
Expand Down
4 changes: 2 additions & 2 deletions src/EasilyNET.Core/PageResult/PageInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ public class PageInfo
/// <summary>
/// 每页数据量
/// </summary>
public int PageSize { get; set; }
public int Size { get; set; }

/// <summary>
/// 跳过的数据量
/// </summary>
public int Skip => (Current - 1) * PageSize;
public int Skip => (Current - 1) * Size;
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion src/EasilyNET.Mongo.GridFS/GridFSController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public virtual async Task<object> Infos(InfoSearch info, CancellationToken cance
.FindAsync(f, new()
{
Sort = Builders<GridFSItemInfo>.Sort.Descending(c => c.CreateTime),
Limit = info.PageSize,
Limit = info.Size,
Skip = info.Skip
}, cancellationToken)
.GetAwaiter().GetResult().ToListAsync(cancellationToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/// <summary>
/// MongoDb的一些静态默认参数
/// </summary>
internal static class EasilyNETConstant
internal static class Constant
{
/// <summary>
/// MongoDB一些转换配置
Expand Down
32 changes: 32 additions & 0 deletions src/EasilyNET.Mongo/EasilyMongoContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;

// ReSharper disable ClassNeverInstantiated.Global

namespace EasilyNET.Mongo;

/// <summary>
/// mongodb base context
/// </summary>
public partial class EasilyMongoContext
{
/// <summary>
/// MongoClient
/// </summary>
public IMongoClient Client { get; private set; } = default!;

/// <summary>
/// 获取链接字符串或者HoyoMongoSettings中配置的特定名称数据库或默认数据库
/// </summary>
public IMongoDatabase Database { get; private set; } = default!;

internal static T CreateInstance<T>(IServiceProvider provider, MongoClientSettings settings, string dbName, params object[] parameters) where T : EasilyMongoContext
{
// 可支持非默认无参构造函数的DbContext
var t = ActivatorUtilities.CreateInstance<T>(provider, parameters);
// var t = Activator.CreateInstance<T>();
t.Client = new MongoClient(settings);
t.Database = t.Client.GetDatabase(dbName);
return t;
}
}
Original file line number Diff line number Diff line change
@@ -1,32 +1,21 @@
using Microsoft.Extensions.DependencyInjection;
using MongoDB.Driver;
using MongoDB.Driver;

// ReSharper disable ClassNeverInstantiated.Global

namespace EasilyNET.Mongo;

/// <summary>
/// mongodb base context
/// DbContext的一些方法,便于简化代码
/// </summary>
public class EasilyNETMongoContext
public partial class EasilyMongoContext
{
/// <summary>
/// MongoClient
/// </summary>
public IMongoClient Client { get; private set; } = default!;

/// <summary>
/// 获取链接字符串或者HoyoMongoSettings中配置的特定名称数据库或默认数据库
/// </summary>
public IMongoDatabase Database { get; private set; } = default!;

/// <summary>
/// 获取IMongoCollection
/// </summary>
/// <typeparam name="TDocument">实体</typeparam>
/// <param name="name">集合名称</param>
/// <returns></returns>
protected IMongoCollection<TDocument> Collection<TDocument>(string name)
protected IMongoCollection<TDocument> GetCollection<TDocument>(string name)
{
#if NET7_0_OR_GREATER
ArgumentException.ThrowIfNullOrEmpty(name, nameof(name));
Expand All @@ -51,13 +40,25 @@ public IMongoDatabase GetDatabase(string name)
return Client.GetDatabase(name);
}

internal static T CreateInstance<T>(IServiceProvider provider, MongoClientSettings settings, string dbName, params object[] parameters) where T : EasilyNETMongoContext
/// <summary>
/// 同步方式获取一个已开启事务的Session
/// </summary>
/// <returns></returns>
public IClientSessionHandle GetStartedSession()
{
var session = Client.StartSession();
session.StartTransaction();
return session;
}

/// <summary>
/// 异步方式获取一个已开启事务的Session
/// </summary>
/// <returns></returns>
public async Task<IClientSessionHandle> GetStartedSessionAsync()
{
// 可支持非默认无参构造函数的DbContext
var t = ActivatorUtilities.CreateInstance<T>(provider, parameters);
// var t = Activator.CreateInstance<T>();
t.Client = new MongoClient(settings);
t.Database = t.Client.GetDatabase(dbName);
return t;
var session = await Client.StartSessionAsync();
session.StartTransaction();
return session;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;

#if !NETSTANDARD
#pragma warning disable CA1822
#endif
Expand All @@ -13,7 +12,7 @@ namespace EasilyNET.Mongo;
/// <summary>
/// Mongodb配置选项
/// </summary>
public sealed class EasilyNETMongoOptions
public sealed class EasilyMongoOptions
{
private static bool TypesFirst { get; set; }

Expand Down Expand Up @@ -51,7 +50,7 @@ public List<Type> ObjectIdToStringTypes
internal Dictionary<string, ConventionPack> ConventionRegistry { get; } = new()
{
{
$"{EasilyNETConstant.Pack}-{ObjectId.GenerateNewId()}", new()
$"{Constant.Pack}-{ObjectId.GenerateNewId()}", new()
{
new CamelCaseElementNameConvention(), // 驼峰名称格式
new IgnoreExtraElementsConvention(true), // 忽略掉实体中不存在的字段
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ namespace EasilyNET.Mongo;
/// <summary>
/// MongoDB注册时使用的一些参数配置
/// </summary>
public sealed class EasilyNETMongoParams
public sealed class EasilyMongoParams
{
/// <summary>
/// DbContextOptions
/// </summary>
// ReSharper disable once UnusedAutoPropertyAccessor.Global
public Action<EasilyNETMongoOptions>? Options { get; set; }
public Action<EasilyMongoOptions>? Options { get; set; }

/// <summary>
/// 当前主要用于支持 SkyAPMSkyApm.Diagnostics.MongoDB,请直接填入: cb => cb.Subscribe(new DiagnosticsActivityEventSubscriber());
Expand All @@ -29,7 +29,7 @@ public sealed class EasilyNETMongoParams
/// <summary>
/// 数据库名称
/// </summary>
public string DatabaseName { get; set; } = EasilyNETConstant.DbName;
public string DatabaseName { get; set; } = Constant.DbName;

/// <summary>
/// DBContext的构造函数参数,用于支持自定义非无参构造函数的DbContext
Expand Down
26 changes: 13 additions & 13 deletions src/EasilyNET.Mongo/MongoServiceExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ public static class MongoServiceExtensions
/// <param name="configuration">IConfiguration</param>
/// <param name="param">其他参数</param>
/// <returns></returns>
public static IServiceCollection AddMongoContext<T>(this IServiceCollection services, IServiceProvider provider, IConfiguration configuration, Action<EasilyNETMongoParams>? param = null)
where T : EasilyNETMongoContext
public static IServiceCollection AddMongoContext<T>(this IServiceCollection services, IServiceProvider provider, IConfiguration configuration, Action<EasilyMongoParams>? param = null)
where T : EasilyMongoContext
{
var connStr = ConnectionString(configuration);
_ = services.AddMongoContext<T>(provider, connStr, param);
Expand All @@ -52,17 +52,17 @@ public static IServiceCollection AddMongoContext<T>(this IServiceCollection serv
/// <param name="settings">HoyoMongoClientSettings</param>
/// <param name="param">其他参数</param>
/// <returns></returns>
public static IServiceCollection AddMongoContext<T>(this IServiceCollection services, IServiceProvider provider, MongoClientSettings settings, Action<EasilyNETMongoParams>? param = null)
where T : EasilyNETMongoContext
public static IServiceCollection AddMongoContext<T>(this IServiceCollection services, IServiceProvider provider, MongoClientSettings settings, Action<EasilyMongoParams>? param = null)
where T : EasilyMongoContext
{
if (!settings.Servers.Any()) throw new("mongo server address can't be empty!");
var dbOptions = new EasilyNETMongoOptions();
var options = new EasilyNETMongoParams();
var dbOptions = new EasilyMongoOptions();
var options = new EasilyMongoParams();
param?.Invoke(options);
options.Options?.Invoke(dbOptions);
RegistryConventionPack(dbOptions);
settings.ClusterConfigurator = options.ClusterBuilder ?? settings.ClusterConfigurator;
var db = EasilyNETMongoContext.CreateInstance<T>(provider, settings, options.DatabaseName, options.ContextParams.ToArray());
var db = EasilyMongoContext.CreateInstance<T>(provider, settings, options.DatabaseName, options.ContextParams.ToArray());
_ = services.AddSingleton(db).AddSingleton(db.Database).AddSingleton(db.Client);
return services;
}
Expand All @@ -76,11 +76,11 @@ public static IServiceCollection AddMongoContext<T>(this IServiceCollection serv
/// <param name="connStr">链接字符串</param>
/// <param name="param">其他参数</param>
/// <returns></returns>
public static IServiceCollection AddMongoContext<T>(this IServiceCollection services, IServiceProvider provider, string connStr, Action<EasilyNETMongoParams>? param = null)
where T : EasilyNETMongoContext
public static IServiceCollection AddMongoContext<T>(this IServiceCollection services, IServiceProvider provider, string connStr, Action<EasilyMongoParams>? param = null)
where T : EasilyMongoContext
{
var options = new EasilyNETMongoParams();
var dbOptions = new EasilyNETMongoOptions();
var options = new EasilyMongoParams();
var dbOptions = new EasilyMongoOptions();
param?.Invoke(options);
options.Options?.Invoke(dbOptions);
RegistryConventionPack(dbOptions);
Expand All @@ -97,15 +97,15 @@ public static IServiceCollection AddMongoContext<T>(this IServiceCollection serv
return services;
}

private static void RegistryConventionPack(EasilyNETMongoOptions options)
private static void RegistryConventionPack(EasilyMongoOptions options)
{
foreach (var item in options.ConventionRegistry)
ConventionRegistry.Register(item.Key, item.Value, _ => true);
if (!options.DefaultConventionRegistry) ConventionRegistry.Remove(options.ConventionRegistry.First().Key);
ConventionRegistry.Register($"easily-id-pack-{ObjectId.GenerateNewId()}", new ConventionPack
{
new StringObjectIdIdGeneratorConvention() //ObjectId → String mapping ObjectId
}, x => !EasilyNETMongoOptions.ObjIdToStringTypes.Contains(x));
}, x => !EasilyMongoOptions.ObjIdToStringTypes.Contains(x));
if (first) return;
BsonSerializer.RegisterSerializer(new DateTimeSerializer(DateTimeKind.Local)); //to local time
BsonSerializer.RegisterSerializer(new DecimalSerializer(BsonType.Decimal128)); //decimal to decimal default
Expand Down

0 comments on commit 1346968

Please sign in to comment.