思考一种好的架构(三)
这节说下最最最核心的库
数据持久化ORM
其实还有很多关键点没说,但是我都跳过了,先说实现场景,再说架构,由浅入深
这里我使用的是Chloe.ORM,用起来比较顺手,也很轻,便于扩展,没有太大的问题,可以很方便的做事件(读写分离)CQRS,(工作单元)WorkOfUnit
/// <summary> /// 单次请求中DC上下配置对象 /// </summary> public interface IDCScoped: IDbConnectionFactory { /// <summary> /// 数据库连接字符串 /// </summary> string ConnectionString { get; } /// <summary> /// 操作类型 /// </summary> DCOperationType OperationType { get; } /// <summary> /// 选择操作类型 /// </summary> /// <param name="connectionString"></param> /// <param name="operationType"></param> void SelectOpeation(string connectionString, DCOperationType operationType); }
/// <summary> /// 数据库范围 /// </summary> public class DCScope : IDCScoped { /// <summary> /// 数据库连接上下字符串 /// </summary> public string ConnectionString { get;private set; } /// <summary> /// 操作类型 /// </summary> public DCOperationType OperationType { get; private set; } /// <summary> /// 创建DC /// </summary> /// <returns></returns> public IDbConnection CreateConnection() { return new MySqlConnection(ConnectionString); } /// <summary> /// 选择操作 /// </summary> /// <param name="connectionString"></param> /// <param name="operationType"></param> public void SelectOpeation(string connectionString, DCOperationType operationType) { this.ConnectionString = connectionString; this.OperationType = operationType; } } /// <summary> /// DC操作类型 /// </summary> public enum DCOperationType { /// <summary> /// 读操作 /// </summary> Query = 0, /// <summary> /// 写操作 /// </summary> Command=1 }
public static class IQueryExtend { public static IQuery<T> EmptyCheck<T>(this IQuery<T> query,object judgeValue, Expression<Func<T, bool>> predicate) { if (judgeValue!=null) { return query.Where(predicate); } return query; } }
这个只是一个非空判断的扩展Where方法,单独写出来只是为了表示Chloe.ORM一切都归它管,扩展方法也是
public static class Startup { public static void ConfigureServices(IServiceCollection services) { services.AddScoped<IDCScoped, DCScope>(); services.AddScoped<IDbContext>(x=> new MySqlContext(x.GetService<IDCScoped>())); } public static void Configure(IApplicationBuilder app, IHostingEnvironment env) { } }
这个注入了IDScoped对象和IDbContext对象
IDScoped 是保存每次需要数据库的信息
ORM.Chloe.DoMain
负责维护一个数据库上下文和它的生命周期,Chloe.ORM的扩展也归它管,但是具体要选哪个数据库创建对象就不归它管了,谁爱管谁管,反正我不负责选则数据库的业务