【发布时间】:2018-05-01 13:16:14
【问题描述】:
我有以下类声明和单元测试:
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 为 false,但 areBothNestedInstancesSame 为 true。
我还在 Web Api 控制器操作中对此进行了测试:
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 自动创建的嵌套容器,以便为每个服务返回一个新实例瞬态生命周期。
谁能帮我理解:1)为什么这是预期的默认行为以及如何使嵌套容器每次都返回一个新实例;或 2) 为什么我不希望嵌套容器每次都返回一个新实例是显而易见的?
谢谢
【问题讨论】:
-
所以,我看到 AlwaysUnique 是导致嵌套容器返回唯一实例的生命周期。我仍然不明白将默认设置为 ContainerScoped 的原因。
-
我在将 StructureMap.Microsoft.DependencyInjection 库用于 asp.net core 2.0 时看到了相同的行为。您是否能够理清为什么瞬态和容器作用域的行为相同?
-
我不是,但行为是一致的,它符合我们真正想要的行为,所以我没有花太多时间在它上面。
标签: c# ioc-container structuremap transient