aspire .net 中使用 sqlsugar 返回

SqlSugar 处理完成
3 1033

1.必要包的:Aspire.Npgsql 和 SqlSugarCoreNoDrive
2.配置使用 Aspire.Npgsql 自带的数据库追踪

// 注册 Aspire 官方 Npgsql DataSource(用于追踪/指标/健康检查)platformAdminConnStr 是链接字符串名称

builder.AddNpgsqlDataSource("platformAdminConnStr");
// IOC 注册 Sqlsugar 

public static IServiceCollection AddPlatformAdminDbContext(

    this IServiceCollection services,

    IConfiguration configuration,

    string connectionName = "platformAdminConnStr"

)

{

    var connectionString =

        configuration.GetConnectionString(connectionName)

        ?? throw new InvalidOperationException($"缺少连接字符串:{connectionName}");


    //注册上下文:AOP里面可以获取IOC对象

    services.AddHttpContextAccessor();


    // 注册SqlSugarClient

    services.AddScoped<ISqlSugarClient>(s =>

    {

        //  Program 注册 AddNpgsqlDataSource,复用官方 tracing/metrics

        var dataSource = s.GetService<NpgsqlDataSource>();

        Func<NpgsqlConnection> connectionFactory =

            dataSource != null

                ? () => dataSource.CreateConnection()

                : () => new NpgsqlConnection(connectionString);


        SqlSugarClient sqlSugar = new SqlSugarClient(

            new ConnectionConfig()

            {

                DbType = SqlSugar.DbType.PostgreSQL,

                ConnectionString = connectionString,

                IsAutoCloseConnection = true,

            }.UseCache(s), // 🗄️ 配置二级缓存服务(自动清理缓存)

            db =>

            {

                db.Ado.Connection ??= connectionFactory(); // 让 SqlSugar 使用 DataSource 连接,便于 OTel 采集


                var logger = s.GetRequiredService<ILogger<SqlSugarClient>>();


                db.Aop.OnLogExecuting = (sql, pars) =>

                {

                    var formattedSql = UtilMethods.GetNativeSql(sql, pars);

                    var parameters =

                        pars?.Length > 0

                            ? string.Join(

                                ", ",

                                pars.Select(p => $"{p.ParameterName}={p.Value}")

                            )

                            : "none";


                    logger.LogInformation(

                        "SqlSugar SQL: {Sql}; Params: {Params}",

                        formattedSql,

                        parameters

                    );

                };


                db.Aop.OnError = exp =>

                {

                    logger.LogError(exp, "SqlSugar 执行错误");

                };


                db.Aop.OnLogExecuted = (sql, pars) =>

                {

                    logger.LogDebug("SqlSugar SQL 执行完成");

                };

                // 全局查询过滤器:软删除

                db.QueryFilter.AddTableFilter<Administrator>(x => x.IsDeleted == false);

                db.QueryFilter.AddTableFilter<ServerRoute>(x => x.IsDeleted == false);

            }

        );

        sqlSugar.Ado.Connection ??= connectionFactory(); // 兜底

        return sqlSugar;

    });


    return services;

}

热忱回答3

  • 我已经试过了,可以完美运行

    0 回复
  • // 注册 Aspire 官方 Npgsql DataSource(用于 tracing / metrics / health checks)

    // platformAdminConnStr 是连接字符串名称

    builder.AddNpgsqlDataSource("platformAdminConnStr");


    // IOC 注册 SqlSugar

    public static IServiceCollection AddPlatformAdminDbContext(

        this IServiceCollection services,

        IConfiguration configuration,

        string connectionName = "platformAdminConnStr"

    )

    {

        var connectionString =

            configuration.GetConnectionString(connectionName)

            ?? throw new InvalidOperationException($"缺少连接字符串:{connectionName}");


        services.AddScoped<ISqlSugarClient>(serviceProvider =>

        {

            // 优先复用 Program 中注册的 NpgsqlDataSource,继承 Aspire 官方 tracing / metrics

            var dataSource = serviceProvider.GetService<NpgsqlDataSource>();

            Func<NpgsqlConnection> connectionFactory =

                dataSource != null

                    ? dataSource.CreateConnection

                    : () => new NpgsqlConnection(connectionString);


            return new SqlSugarClient(

                new ConnectionConfig

                {

                    DbType = SqlSugar.DbType.PostgreSQL,

                    ConnectionString = connectionString,

                    IsAutoCloseConnection = true,

                }.UseCache(serviceProvider), // 配置二级缓存服务(自动清理缓存)

                db =>

                {

                    // 让 SqlSugar 使用 DataSource 创建的连接,便于接入 Aspire.Npgsql 的探测能力

                    db.Ado.Connection ??= connectionFactory();


                    var logger = serviceProvider.GetRequiredService<ILogger<SqlSugarClient>>();


                    db.Aop.OnLogExecuting = (sql, pars) =>

                    {

                        var formattedSql = UtilMethods.GetNativeSql(sql, pars);

                        var parameters =

                            pars?.Length > 0

                                ? string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}"))

                                : "none";


                        logger.LogInformation(

                            "SqlSugar SQL: {Sql}; Params: {Params}",

                            formattedSql,

                            parameters

                        );

                    };


                    db.Aop.OnError = exp =>

                    {

                        logger.LogError(exp, "SqlSugar 执行错误");

                    };


                    db.Aop.OnLogExecuted = (_, _) =>

                    {

                        logger.LogDebug("SqlSugar SQL 执行完成");

                    };


                    // 全局查询过滤器:软删除

                    db.QueryFilter.AddTableFilter<Administrator>(x => x.IsDeleted == false);

                    db.QueryFilter.AddTableFilter<ServerRoute>(x => x.IsDeleted == false);

                }

            );

        });


        return services;

    }


    0 回复
  • 删除了多余代码


    0 回复