You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Program.cs构建App前解析DI获取Blazor动态级联值?

在.NET 8 RC2根级联值中通过DI获取动态数据的解决方案

实现步骤

  1. 注册数据访问服务
    先将负责从数据库获取季节数据的服务注册到DI容器中,示例如下:
// 定义数据访问接口
public interface ISeasonService
{
    CurrentSeasonModel GetCurrentSeason();
}

// 实现数据访问逻辑
public class SeasonService : ISeasonService
{
    private readonly AppDbContext _dbContext;

    // 通过构造函数注入DbContext
    public SeasonService(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public CurrentSeasonModel GetCurrentSeason()
    {
        // 从数据库查询当前季节数据(替换为你的实际业务逻辑)
        var activeSeason = _dbContext.Seasons.FirstOrDefault(s => s.IsActive);
        
        return activeSeason != null 
            ? new CurrentSeasonModel { SelectedStageId = activeSeason.StageId } 
            : new CurrentSeasonModel { SelectedStageId = 65 }; // 兜底默认值
    }
}

在Program.cs中注册DbContext和数据服务:

var builder = WebApplication.CreateBuilder(args);

// 注册数据库上下文(根据你的数据库类型调整配置)
builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 注册季节数据服务
builder.Services.AddScoped<ISeasonService, SeasonService>();
  1. 在根级联值中解析服务获取动态数据
    利用AddCascadingValue委托提供的IServiceProvider参数,直接解析已注册的服务并获取动态数据:
builder.Services.AddCascadingValue(s =>
{
    // 从DI容器中解析数据服务
    var seasonService = s.GetRequiredService<ISeasonService>();
    // 获取数据库中的动态季节数据
    var currentSeason = seasonService.GetCurrentSeason();

    return new CascadingValueSource<CurrentSeasonModel>(
        "abc",
        currentSeason,
        isFixed: true);
});

关键说明

  • AddCascadingValue的委托参数s是框架提供的已初始化完成的IServiceProvider,可以安全解析所有提前注册的服务,无需在builder.Build()之前手动创建实例。
  • 若设置isFixed: true,该级联值只会在首次使用时初始化一次;如果需要实时更新数据,可将isFixed改为false,并确保数据服务方法能返回最新的数据库数据。
  • 所有依赖服务(如DbContext、ISeasonService)必须在调用AddCascadingValue之前完成注册,否则会触发服务未找到的异常。

内容的提问来源于stack exchange,提问作者nam vo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:33:17