目录
一、模块配置服务
二、配置服务的编写(配置ORM)
三、高层代码的运用(ORM实例查询 & 获取字符串)
一、模块配置服务
BookStoreHttpApiHostModule
二、配置服务的编写(配置ORM)
(以freesql为例子)
public static class MultiDBSetup
{
public static void AddMultiDB(this IServiceCollection services)
{
var configuration = services.GetConfiguration();
var conn = configuration.GetSection("ConnectionStrings").GetChildren().FirstOrDefault().Value;//获取连接字符串
IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.SqlServer, conn)
.UseMonitorCommand(cmd => Console.WriteLine($"Sql:{cmd.CommandText}"))
.UseAutoSyncStructure(false) //取消自动同步实体结构到数据库,只有CRUD时才会生成表
.Build();
services.AddSingleton<IFreeSql>(fsql);//将这个实例注册为单例服务,以便其他服务可以通过依赖注入获取 IFreeSql 的实例
}
}
连接字符串格式:
{
"App": {
"CorsOrigins": "https://*.BookStore.com"
},
"ConnectionStrings": {
"Default": "Server=localhost; Database=TestABP;Trusted_Connection=True;TrustServerCertificate=true"
},
"Redis": {
"Configuration": "127.0.0.1"
}
}
关键代码:
var conn = configuration.GetSection("ConnectionStrings").GetChildren().FirstOrDefault()?.Value;//获取连接字符串
三、高层代码的运用(ORM实例查询 & 获取字符串)
namespace Acme.BookStore.Books
{
[Route("api/freesql")]
public class BookSearchByFreesql : ApplicationService
{
private readonly IFreeSql _fsql;
private readonly IConfiguration _configuration;
public BookSearchByFreesql(IFreeSql fsql,IConfiguration configuration)
{
_fsql = fsql;
_configuration = configuration;
}
/// <summary>
/// 获取书本(freesql)
/// </summary>
/// <returns></returns>
[Route("freesqlgetbook")]
[HttpGet]
public async Task<List<AppBooks>> GetListAsync()
{
try
{
var books = await _fsql.Select<AppBooks>().ToListAsync();//通过注入的IFreeSql实例进行查询
return books;
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
}
/// <summary>
/// 获取连接字符串(appsetting.json)
/// </summary>
/// <returns></returns>
[Route("freesqlgetconn")]
[HttpGet]
public async Task<string> GetConn()
{
return _configuration.GetSection("ConnectionStrings").GetChildren().FirstOrDefault()?.Value;//通过注入的IConfiguration获取字符串
}
}
}