Skip to content

Commit

Permalink
refactor: 精简 PetaPoco 数据服务代码
Browse files Browse the repository at this point in the history
  • Loading branch information
ArgoZhang committed Apr 23, 2024
1 parent cf9dffe commit fb40a54
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 49 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,28 @@
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone

using BootstrapAdmin.DataAccess.PetaPoco;
using BootstrapAdmin.DataAccess.PetaPoco.Services;
using BootstrapAdmin.Web.Core;
using BootstrapBlazor.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using PetaPoco;
using System.Collections.Specialized;
using System.Data.Common;
using System.Text;

namespace Microsoft.Extensions.DependencyInjection;

/// <summary>
///
/// PetaPoco ORM 扩展数据服务类
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
///
/// 增加 PetaPoco 数据服务
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddPetaPocoDataAccessServices(this IServiceCollection services)
{
services.TryAddSingleton<IDBManager, DBManagerService>();

// 增加数据服务
// 增加数据服务(未复用 Blazor 扩展 PetaPoco 服务有一些特殊处理)
services.AddSingleton(typeof(IDataService<>), typeof(DefaultDataService<>));

// 增加缓存服务
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,8 @@

namespace BootstrapAdmin.DataAccess.PetaPoco.Services;

internal class DBManagerService : IDBManager
internal class DBManagerService(IConfiguration configuration, ILogger<DBManagerService> logger, IWebHostEnvironment host) : IDBManager
{
private IConfiguration Configuration { get; set; }

private ILogger<DBManagerService> Logger { get; set; }

private IWebHostEnvironment WebHost { get; set; }

public DBManagerService(IConfiguration configuration, ILogger<DBManagerService> logger, IWebHostEnvironment host)
{
Configuration = configuration;
Logger = logger;
WebHost = host;
}

/// <summary>
/// 创建 IDatabase 实例方法
/// </summary>
Expand All @@ -38,12 +25,12 @@ public DBManagerService(IConfiguration configuration, ILogger<DBManagerService>
/// <returns></returns>
public IDatabase Create(string connectionName = "ba", bool keepAlive = false)
{
var conn = Configuration.GetConnectionString(connectionName) ?? throw new ArgumentNullException(nameof(connectionName));
var conn = configuration.GetConnectionString(connectionName) ?? throw new ArgumentNullException(nameof(connectionName));

var option = DatabaseConfiguration.Build();
option.UsingDefaultMapper<BootstrapAdminConventionMapper>();

// connectionstring
// connectionString
option.UsingConnectionString(conn);

// provider
Expand All @@ -58,9 +45,9 @@ public IDatabase Create(string connectionName = "ba", bool keepAlive = false)
[nameof(db.LastCommand)] = db.LastCommand,
[nameof(db.LastArgs)] = string.Join(",", db.LastArgs)
});
Logger.LogError(e.Exception, "{Message}", message);
logger.LogError(e.Exception, "{Message}", message);
};
if (WebHost.IsDevelopment())
if (host.IsDevelopment())
{
db.CommandExecuted += (sender, args) =>
{
Expand All @@ -69,8 +56,8 @@ public IDatabase Create(string connectionName = "ba", bool keepAlive = false)
{
parameters.AppendFormat("{0}: {1} ", p.ParameterName, p.Value);
}
Logger.LogInformation("{CommandText}", args.Command.CommandText);
Logger.LogInformation("{CommandArgs}", parameters.ToString());
logger.LogInformation("{CommandText}", args.Command.CommandText);
logger.LogInformation("{CommandArgs}", parameters.ToString());
};
};
return db;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,8 @@ namespace BootstrapAdmin.DataAccess.PetaPoco.Services;
/// <summary>
/// PetaPoco ORM 的 IDataService 接口实现
/// </summary>
class DefaultDataService<TModel> : DataServiceBase<TModel> where TModel : class, new()
class DefaultDataService<TModel>(IDBManager dbManager, IUser userService) : DataServiceBase<TModel> where TModel : class, new()
{
private IDBManager DBManager { get; }

private IUser UserService { get; }

/// <summary>
/// 构造函数
/// </summary>
public DefaultDataService(IDBManager db, IUser userService) => (DBManager, UserService) = (db, userService);

/// <summary>
/// 删除方法
/// </summary>
Expand All @@ -33,7 +24,7 @@ public override Task<bool> DeleteAsync(IEnumerable<TModel> models)
{
// 通过模型获取主键列数据
// 支持批量删除
using var db = DBManager.Create();
using var db = dbManager.Create();
db.DeleteBatch(models);
return Task.FromResult(true);
}
Expand All @@ -48,11 +39,11 @@ public override async Task<bool> SaveAsync(TModel model, ItemChangedType changed
{
if (model is User user)
{
UserService.SaveUser(user.UserName, user.DisplayName, user.NewPassword);
userService.SaveUser(user.UserName, user.DisplayName, user.NewPassword);
}
else
{
using var db = DBManager.Create();
using var db = dbManager.Create();
if (changedType == ItemChangedType.Add)
{
await db.InsertAsync(model);
Expand Down Expand Up @@ -80,7 +71,7 @@ public override async Task<QueryData<TModel>> QueryAsync(QueryPageOptions option
IsSearch = option.Searches.Any() || option.CustomerSearches.Any()
};

using var db = DBManager.Create();
using var db = dbManager.Create();
if (option.IsPage)
{
var items = await db.PageAsync<TModel>(option.PageIndex, option.PageItems, option.ToFilter(), option.SortName, option.SortOrder);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ public static IServiceCollection AddBootstrapBlazorAdmin(this IServiceCollection

// 增加 BootstrapApp 上下文服务
services.AddScoped<BootstrapAppContext>();
// });

// 增加 PetaPoco 数据服务
services.AddPetaPocoDataAccessServices();

// 增加 EFCore 数据服务
//services.AddEFCoreDataAccessServices((provider, option) =>
Expand All @@ -68,10 +72,6 @@ public static IServiceCollection AddBootstrapBlazorAdmin(this IServiceCollection
// 调试sql语句输出
// builder.UseMonitorCommand(cmd => System.Console.WriteLine(cmd.CommandText));
//#endif
// });

// 增加 PetaPoco 数据服务
services.AddPetaPocoDataAccessServices();

return services;
}
Expand Down

0 comments on commit fb40a54

Please sign in to comment.