/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

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