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

将ConsumeContext注入到Scoped对象中的技术实现问询

我最近在尝试创建一些Scoped对象,并注入ConsumeContext,这样后续就能从实例中用它来发送消息了。以下是我的实现思路:

定义ScopedObject类

首先我先定义了ScopedObject类,代码如下:

public class ScopedObject {
    public Guid ScopeId { get; set; } = NewId.NextGuid();
    private ConsumeContext _context;
    public void SetContext(ConsumeContext context) {
        _context = context;
    }
    public Task DoSomeStaff() {
        if (_context == null) throw new NullReferenceException(nameof(_context));
        // 这里编写具体的业务逻辑,比如通过_context发送消息
    }
}

一点优化建议

其实如果能通过构造函数注入的方式传入ConsumeContext会更稳妥,这样可以在对象创建时就确保依赖存在,避免后续调用DoSomeStaff时出现空引用异常,修改后的代码大概是这样:

public class ScopedObject {
    public Guid ScopeId { get; set; } = NewId.NextGuid();
    private readonly ConsumeContext _context;

    // 构造函数注入,确保_context不会为null
    public ScopedObject(ConsumeContext context) {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public Task DoSomeStaff() {
        // 直接使用_context即可,无需空检查
        // 编写具体业务逻辑
    }
}

这样一来,依赖注入容器在创建ScopedObject实例时就会自动注入ConsumeContext,不需要手动调用SetContext,也从根源上避免了空引用的问题。

内容的提问来源于stack exchange,提问作者A. Wheatman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:25:48