PageRenderTime 421ms CodeModel.GetById 79ms app.highlight 4ms RepoModel.GetById 212ms app.codeStats 0ms

/src/UnitTests/IOC/ScopeTests.cs

http://github.com/philiplaureano/LinFu
C# | 71 lines | 53 code | 12 blank | 6 comment | 0 complexity | d7c387503354de8dd19a0e9c169bead7 MD5 | raw file
 1using System;
 2using System.Threading;
 3using LinFu.IoC;
 4using LinFu.IoC.Interfaces;
 5using Moq;
 6using Xunit;
 7
 8namespace LinFu.UnitTests.IOC
 9{
10    public class ScopeTests : BaseTestFixture
11    {
12        [Fact]
13        public void ScopeShouldCallDisposableOnScopedObject()
14        {
15            var mock = new Mock<IDisposable>();
16            mock.Expect(disposable => disposable.Dispose());
17
18            var container = new ServiceContainer();
19            container.AddService(mock.Object);
20
21            using (var scope = container.GetService<IScope>())
22            {
23                // Create the service instance
24                var instance = container.GetService<IDisposable>();
25            }
26        }
27
28        [Fact]
29        public void ScopeShouldNeverCallDisposableOnNonScopedObject()
30        {
31            var mock = new Mock<IDisposable>();
32            var container = new ServiceContainer();
33            container.AddService(mock.Object);
34
35            using (var scope = container.GetService<IScope>())
36            {
37            }
38
39            // Create the service instance OUTSIDE the scope
40            // Note: this should never be disposed
41            var instance = container.GetService<IDisposable>();
42        }
43
44        [Fact]
45        public void ScopeShouldNeverCallDisposableOnScopedObjectCreatedInAnotherThread()
46        {
47            var mock = new Mock<IDisposable>();
48
49            var container = new ServiceContainer();
50            container.AddService(mock.Object);
51
52            using (var scope = container.GetService<IScope>())
53            {
54                var signal = new ManualResetEvent(false);
55                WaitCallback callback = state =>
56                {
57                    // Create the service instance
58                    var instance = container.GetService<IDisposable>();
59                    signal.Set();
60                };
61
62                ThreadPool.QueueUserWorkItem(callback);
63
64                // Wait for the thread to execute
65                WaitHandle.WaitAny(new WaitHandle[] {signal});
66            }
67
68            // The instance should never be disposed
69        }
70    }
71}