
using (ILifetimeScope parentScope = CreateContainer()) { using (ILifetimeScope childScope1 = parentScope.BeginLifetimeScope(b => b.RegisterType<MyType>().SingleInstance())) using (ILifetimeScope childScope2 = parentScope.BeginLifetimeScope(b => b.RegisterType<MyType>().SingleInstance())) { MyType result1 = childScope1.Resolve<MyType>(); MyType result2 = childScope2.Resolve<MyType>(); result1.ShouldNotReferTo(result2); } }
[Test] public void InstancePerDependency_NewInstanceCreatedEveryTime() { using (ILifetimeScope scope = CreateContainer(builder => builder.RegisterType<MyType>())) { MyType instance1 = scope.Resolve<MyType>(); MyType instance2 = scope.Resolve<MyType>(); instance1.ShouldNotReferTo(instance2); } }
[Test] public void SingleInstance_IsScopedToWhereRegistrationOccurs() { using (ILifetimeScope outerScope = CreateContainer(b => b.RegisterType<MyType>())) { using (ILifetimeScope middleScope = outerScope.BeginLifetimeScope(b => b.RegisterType<MyType>().SingleInstance())) { using (ILifetimeScope innerScope = middleScope.BeginLifetimeScope()) { MyType outerResult = outerScope.Resolve<MyType>(); MyType innerResult = innerScope.Resolve<MyType>(); MyType middleResult = middleScope.Resolve<MyType>(); outerResult.ShouldNotReferTo(middleResult); innerResult.ShouldReferTo(middleResult); } } } }
[Test] public void InstancePerLifetimeScope_OneInstancePerScope() { using (ILifetimeScope outerScope = CreateContainer(b => b.RegisterType<MyType>().InstancePerLifetimeScope())) { using (ILifetimeScope innerScope = outerScope.BeginLifetimeScope()) { MyType outerInstance1 = outerScope.Resolve<MyType>(); MyType outerInstance2 = outerScope.Resolve<MyType>(); MyType innerInstance = innerScope.Resolve<MyType>(); outerInstance1.ShouldReferTo(outerInstance2); innerInstance.ShouldNotReferTo(outerInstance1); } } }
