public void Fact1() { services.AddScoped <TestService>(); using (var provider = services.BuildServiceProvider()) { var rootInstance = provider.GetService <TestService>(); using (var sut = new ServiceScopeExtension(provider)) { Assert.NotSame(provider, sut.ScopedServiceProvider); var scopedService1 = sut.ScopedServiceProvider.GetService <TestService>(); var scopedService2 = sut.ScopedServiceProvider.GetService <TestService>(); Assert.NotSame(rootInstance, scopedService1); Assert.Same(scopedService1, scopedService1); } } }
/// <summary> /// Returns a service object given the specified <see cref="InstanceContext"/> object. /// </summary> /// <param name="instanceContext">The current <see cref="InstanceContext"/> object.</param> /// <param name="message">The message that triggered the creation of a service object.</param> /// <returns>The service object.</returns> /// <exception cref="ArgumentNullException"> /// Thrown if <paramref name="instanceContext" /> is <see langword="null" />. /// </exception> public object GetInstance(InstanceContext instanceContext, Message message) { if (instanceContext == null) { throw new ArgumentNullException(nameof(instanceContext)); } var serviceScopeExtensions = new ServiceScopeExtension(serviceProvider); instanceContext.Extensions.Add(serviceScopeExtensions); try { return(serviceFactory(serviceScopeExtensions.ScopedServiceProvider)); } catch (Exception) { serviceScopeExtensions.Dispose(); instanceContext.Extensions.Remove(serviceScopeExtensions); throw; } }