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

标签 c# ioc-container structuremap transient

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

    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/

相关文章:

c# - mvc 中的复选框返回 null

c++ - 依赖注入(inject)库的正确比喻是什么?

c# - 为什么 BaseController 的重载构造函数没有被执行?

c# - NEST不推荐使用的字段[include]

c# - Visual Studio 2010 在 exe 中包含文件

c# - 使用 IoC 和 Dependency Injection,如何在不违反 Open-Closed 原则的情况下用新的实现层包装代码?

c# - 使用 StructureMap.DependencyInjection 在 C# dotnet core 2.0 中简单代理类依赖注入(inject)

structuremap - ASP.NET WebApi 操作过滤器和依赖范围

c# - MultiBinding 转换器未绑定(bind)到 DataTemplate 中的 TextBlock

c# - 将 IoC 容器用于插件架构