|
| 1 | +using Microsoft.Extensions.DependencyInjection; |
| 2 | +using System.Collections.Generic; |
| 3 | +using Unity.Microsoft.DependencyInjection; |
| 4 | +using Xunit; |
| 5 | + |
| 6 | +namespace UnitTests |
| 7 | +{ |
| 8 | + public class ScopedDepencencyTests |
| 9 | + { |
| 10 | + [Fact] |
| 11 | + public void ScopedDependencyFromTransientFactoryNotSharedAcrossScopes() |
| 12 | + { |
| 13 | + // Arrange |
| 14 | + var collection = new TestServiceCollection() |
| 15 | + .AddTransient<ITransient>(CreateTransientFactory) |
| 16 | + .AddScoped<IScoped, Scoped>(); |
| 17 | + |
| 18 | + var provider = collection.BuildServiceProvider(); |
| 19 | + |
| 20 | + // Act |
| 21 | + ITransient transient1 = null; |
| 22 | + ITransient transient2a = null; |
| 23 | + ITransient transient2b = null; |
| 24 | + |
| 25 | + using (var scope1 = provider.CreateScope()) |
| 26 | + { |
| 27 | + transient1 = scope1.ServiceProvider.GetService<ITransient>(); |
| 28 | + } |
| 29 | + |
| 30 | + using (var scope2 = provider.CreateScope()) |
| 31 | + { |
| 32 | + transient2a = scope2.ServiceProvider.GetService<ITransient>(); |
| 33 | + transient2b = scope2.ServiceProvider.GetService<ITransient>(); |
| 34 | + } |
| 35 | + |
| 36 | + // Assert |
| 37 | + Assert.NotSame(transient1, transient2a); |
| 38 | + Assert.NotSame(transient2a, transient2b); |
| 39 | + Assert.NotSame(transient1.ScopedDependency, transient2a.ScopedDependency); |
| 40 | + Assert.Same(transient2a.ScopedDependency, transient2b.ScopedDependency); |
| 41 | + } |
| 42 | + |
| 43 | + private ITransient CreateTransientFactory(System.IServiceProvider provider) |
| 44 | + { |
| 45 | + return provider.GetRequiredService<Transient>(); |
| 46 | + } |
| 47 | + |
| 48 | + public interface ITransient |
| 49 | + { |
| 50 | + IScoped ScopedDependency { get; } |
| 51 | + } |
| 52 | + |
| 53 | + public class Transient : ITransient |
| 54 | + { |
| 55 | + public Transient(IScoped scoped) |
| 56 | + { |
| 57 | + ScopedDependency = scoped; |
| 58 | + } |
| 59 | + |
| 60 | + public IScoped ScopedDependency { get; } |
| 61 | + } |
| 62 | + |
| 63 | + public interface IScoped { } |
| 64 | + |
| 65 | + public class Scoped : IScoped |
| 66 | + { |
| 67 | + } |
| 68 | + |
| 69 | + } |
| 70 | + |
| 71 | + internal class TestServiceCollection : List<ServiceDescriptor>, IServiceCollection |
| 72 | + { |
| 73 | + } |
| 74 | +} |
0 commit comments