feat: 增加多库服务支持

This commit is contained in:
Argo-Lenovo 2022-06-01 18:49:30 +08:00
parent 371d188d76
commit 9dfd95ce41
2 changed files with 51 additions and 0 deletions

View File

@ -66,6 +66,8 @@ public static class ServiceCollectionExtensions
//// 增加数据服务
//services.AddSingleton(typeof(IDataService<>), typeof(DefaultDataService<>));
// 增加多数据库支持服务
services.AddSingleton<DBManagerService>();
//// 增加业务服务
//services.AddSingleton<IApp, AppService>();

View File

@ -0,0 +1,49 @@
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved.
// Licensed under the LGPL License, Version 3.0. See License.txt in the project root for license information.
// Website: https://admin.blazor.zone
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using PetaPoco;
using PetaPoco.Providers;
using System.Collections.Specialized;
namespace BootstrapClient.DataAccess.PetaPoco.Services;
internal class DBManagerService
{
private IConfiguration Configuration { get; set; }
private ILogger<DBManagerService> Logger { get; set; }
public DBManagerService(IConfiguration configuration, ILogger<DBManagerService> logger)
{
Configuration = configuration;
Logger = logger;
}
/// <summary>
/// 创建 IDatabase 实例方法
/// </summary>
/// <param name="connectionName">连接字符串键值</param>
/// <param name="keepAlive"></param>
/// <returns></returns>
public IDatabase Create(string? connectionName = "client", bool keepAlive = false)
{
var conn = Configuration.GetConnectionString(connectionName) ?? throw new ArgumentNullException(nameof(connectionName));
var source = DatabaseConfiguration.Build();
// connectionstring
source.UsingConnectionString(conn);
// provider
source.UsingProvider<SqlServerDatabaseProvider>();
var db = new Database(source) { KeepConnectionAlive = keepAlive };
db.ExceptionThrown += (sender, args) =>
{
Logger.LogError(args.Exception, $"Last-Cmd: {db.LastCommand}");
};
return db;
}
}