public void ShouldInjectEnumerableWithItemsWithDifferentLifetimes() { // <example4> // since we're using a scoped registration here, // we'll use the ScopedContainer, which establishes // a root scope. var container = new ScopedContainer(); container.RegisterSingleton <MyService1, IMyService>(); container.RegisterScoped <MyService2, IMyService>(); container.RegisterType <MyService3, IMyService>(); // So - each enumerable will contain, in order: // 1) Singleton IMyService // 2) Scoped IMyService // 3) Transient IMyService var fromRoot1 = container.ResolveMany <IMyService>().ToArray(); var fromRoot2 = container.ResolveMany <IMyService>().ToArray(); Assert.Same(fromRoot1[0], fromRoot2[0]); // both scoped objects should be the same because we've resolved // from the root scope Assert.Same(fromRoot1[1], fromRoot2[1]); Assert.NotSame(fromRoot1[2], fromRoot2[2]); using (var childScope = container.CreateScope()) { var fromChildScope1 = childScope.ResolveMany <IMyService>().ToArray(); // singleton should be the same as before, but // the scoped object will be different Assert.Same(fromRoot1[0], fromChildScope1[0]); Assert.NotSame(fromRoot1[1], fromChildScope1[1]); Assert.NotSame(fromRoot1[2], fromChildScope1[2]); var fromChildScope2 = childScope.ResolveMany <IMyService>().ToArray(); // the scoped object will be the same as above Assert.Same(fromChildScope1[0], fromChildScope2[0]); Assert.Same(fromChildScope1[1], fromChildScope2[1]); Assert.NotSame(fromChildScope1[2], fromChildScope2[2]); } // </example4> }
public void DisposableSingletonShouldBeDisposedByRootScope() { // <example4> // In this example we use the disposable ScopedContainer, which // supports all the same functionality as 'Container' except it // also has its own scope, and is therefore disposable. DisposableType result; using (var container = new ScopedContainer()) { container.RegisterSingleton <DisposableType>(); using (var scope = container.CreateScope()) { // singletons force tracking in the // rootmost scope of a scope hierarchy result = scope.Resolve <DisposableType>(); } Assert.False(result.Disposed); } Assert.True(result.Disposed); // </example4> }