gpt4 book ai didi

c# - 为什么在嵌套容器上将 Structuremap 的 Transient 生命周期视为 ContainerScoped?

转载 作者:太空宇宙 更新时间:2023-11-03 12:20:53 25 4
gpt4 key购买 nike

我有以下类声明和单元测试:

    public class Blah { }

[TestMethod]
public void TestMethod1()
{
var container = new Container();

var instance1 = container.GetInstance<Blah>();
var instance2 = container.GetInstance<Blah>();

var areBothInstancesSame = instance1 == instance2;

var nested = container.GetNestedContainer();

var nestedInstance1 = nested.GetInstance<Blah>();
var nestedInstance2 = nested.GetInstance<Blah>();

var areBothNestedInstancesSame = nestedInstance1 == nestedInstance2;
}

当我运行此测试时,areBothInstancesSame 为假,但 areBothNestedInstancesSame 为真。

我还在 Web Api Controller 操作中对此进行了测试:

    public class Blah { }

public IHttpActionResult GetBlah()
{
var scope = this.Request.GetDependencyScope();

var instance1 = (Blah)scope.GetService(typeof(Blah));
var instance2 = (Blah)scope.GetService(typeof(Blah));

var areBothInstancesSame = instance1 == instance2;

return this.Ok();
}

再一次,areBothInstancesSame 为真。

我在 Structuremap 的文档中看到了这个描述,所以我相信它按预期工作,但我不明白为什么会这样,或者如何获取 Web Api 自动创建的嵌套容器以返回每个服务的新实例 transient 生命周期。

任何人都可以帮助我理解:1)为什么这是预期的默认行为以及如何使嵌套容器每次都返回一个新实例;或 2) 为什么很明显我不应该希望嵌套容器每次都返回一个新实例?

谢谢

最佳答案

我能给出的最佳答案是,嵌套 这个词指的是容器的服务,而不一定是容器层次结构,因为它看起来可能是这样(这就是为什么 child containers 也存在的原因)从普通容器获取服务实例将创建一个新实例以及完整的对象图,其中包含所有必需的嵌套服务。无论某些 transient 服务嵌套在对象图中多少次,都只会为该服务类型创建一个实例并在整个图中重复使用。

对于嵌套容器, transient 实例的行为就像它们属于(嵌套在其中)同一个对象图一样,因为它的目的是在一个逻辑请求中使用。

也许这个例子有助于嵌套容器的使用http://structuremap.github.io/the-container/nested-containers/#sec5

基本上存在嵌套容器以确保 transient 服务不会在每次 GetService 调用时获得新实例。

要使嵌套容器每次都返回一个新实例,您应该将服务注册为 AlwaysUnique

关于c# - 为什么在嵌套容器上将 Structuremap 的 Transient 生命周期视为 ContainerScoped?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47356111/

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