gpt4 book ai didi

c# - ninject(或其他 IoC)与任务范围?

转载 作者:太空狗 更新时间:2023-10-29 21:46:09 25 4
gpt4 key购买 nike

我不确定 TPL 表面是否足以使它可行,因此,请随意指出可行的替代模式。 :)

我正在尝试弄清楚是否可以将 Ninject 用于 ctor 注入(inject)的依赖项,理想情况下,这些依赖项的范围应该限定在特定的根/父任务实例中。

它有点类似于 asp.net 请求范围,但在这种情况下,它是一个控制台应用程序,它创建 N 个将并行运行的不同任务。我想知道是否有能力让 Ninject 基于每个根 Task 实例进行运行时依赖注入(inject),这样作为每个任务的一部分创建的对象图共享给定接口(interface)的相同实例,但不同的任务都有单独的实例。

谢谢!

[编辑] 继续搜索,看起来 InNamedScope 可能 是基于“定义对象是其依赖项的范围”的描述的正确答案

最佳答案

如果我正确理解你的问题,InNamedScope 是一个不错的选择。另一种选择是 InCallScope。这blog post对差异进行了很好的讨论:

The named scope lets you define on a binding that the object created by the binding is the scope for other objects that are part of the object tree that is injected into the created object.

Let us see how this works on an example. Imagine that you are creating an Excel like application that has multiple worksheets....

const string ScopeName = "ExcelSheet";
Bind<ExcelSheet>().ToSelf().DefinesNamedScope(ScopeName);
Bind<SheetPresenter>().ToSelf();
Bind<SheetCalculator>().ToSelf();
Bind<SheetDataRepository>().ToSelf().InNamedScope(ScopeName);

此处,SheetDataRepository 使用范围内的 ExcelSheet。这篇文章解释得更详细。

关于c# - ninject(或其他 IoC)与任务范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10656557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com