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

如何无需传递dbContext参数,让TestRepo类访问数据库上下文?

如何让TestRepo无需手动传入_context即可使用数据库上下文?

我现在在ValuesController里调用TestRepo的GetUsers方法获取所有用户列表,目前必须把_context传入TestRepo的构造函数来实例化:

var testRepo = new TestRepo(_context);
return testRepo.GetUsers();

希望能不用手动传递_context给TestRepo,就能让这个类使用_context,请问正确的实现方式是什么?


现有代码

ValuesController.cs

public class ValuesController : ControllerBase
{
    private readonly ApplicationDBContext _context;

    public ValuesController(ApplicationDBContext context)
    {
        _context = context;
    }

    // GET: api/<ValuesController>
    [HttpGet]
    public IEnumerable<User> Get()
    {
        var testRepo = new TestRepo(_context);
        return testRepo.GetUsers();
    }
}

TestRepo.cs

public class TestRepo
{
    private readonly ApplicationDBContext _context;

    public TestRepo(ApplicationDBContext context)
    {
        _context = context;
    }

    public IEnumerable<User> GetUsers()
    {
        return _context.Users.ToList(); ;
    }
}

解决方案:利用依赖注入容器管理实例

核心思路是把TestRepo也注册到依赖注入(DI)容器中,由容器自动处理ApplicationDBContext的传递,不需要在控制器里手动实例化TestRepo。

步骤1:注册TestRepo到DI容器

在项目的启动配置文件(比如Program.cs)中,添加TestRepo的注册:

// 注册数据库上下文(你应该已经有这行代码)
builder.Services.AddDbContext<ApplicationDBContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// 注册TestRepo,使用Scoped生命周期(和DBContext一致)
builder.Services.AddScoped<TestRepo>();

步骤2:修改ValuesController,注入TestRepo

把控制器里的_context替换为注入的TestRepo,不再手动实例化:

public class ValuesController : ControllerBase
{
    private readonly TestRepo _testRepo;

    // 构造函数注入TestRepo
    public ValuesController(TestRepo testRepo)
    {
        _testRepo = testRepo;
    }

    // GET: api/<ValuesController>
    [HttpGet]
    public IEnumerable<User> Get()
    {
        // 直接使用注入的实例,无需手动传_context
        return _testRepo.GetUsers();
    }
}

步骤3:保持TestRepo的构造函数不变

TestRepo依然通过构造函数接收ApplicationDBContext,这个过程会由DI容器自动完成,不需要你手动传递:

public class TestRepo
{
    private readonly ApplicationDBContext _context;

    public TestRepo(ApplicationDBContext context)
    {
        _context = context;
    }

    public IEnumerable<User> GetUsers()
    {
        return _context.Users.ToList();
    }
}

这样修改后,DI容器会自动为TestRepo创建实例并注入所需的ApplicationDBContext,控制器只需要直接使用注入的TestRepo即可,完全不需要手动传递上下文。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:05:17