PageRenderTime 50ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Ninject.Tests/Integration/ThreadScopeTests.cs

https://github.com/developingchris/ninject
C# | 93 lines | 70 code | 23 blank | 0 comment | 0 complexity | 3da69e880109c71c27b44d6fcb5cb822 MD5 | raw file
  1. using System;
  2. using System.Threading;
  3. using Ninject.Activation.Caching;
  4. using Ninject.Tests.Fakes;
  5. using Xunit;
  6. using Xunit.Should;
  7. namespace Ninject.Tests.Integration.ThreadScopeTests
  8. {
  9. public class ThreadScopeContext
  10. {
  11. protected readonly StandardKernel kernel;
  12. public ThreadScopeContext()
  13. {
  14. var settings = new NinjectSettings { CachePruningInterval = TimeSpan.MaxValue };
  15. kernel = new StandardKernel(settings);
  16. }
  17. }
  18. public class WhenServiceIsBoundWithThreadScope : ThreadScopeContext
  19. {
  20. [Fact]
  21. public void FirstActivatedInstanceIsReusedWithinThread()
  22. {
  23. kernel.Bind<IWeapon>().To<Sword>().InThreadScope();
  24. IWeapon weapon1 = null;
  25. IWeapon weapon2 = null;
  26. ThreadStart callback = () =>
  27. {
  28. weapon1 = kernel.Get<IWeapon>();
  29. weapon2 = kernel.Get<IWeapon>();
  30. };
  31. var thread = new Thread(callback);
  32. thread.Start();
  33. thread.Join();
  34. weapon1.ShouldNotBeNull();
  35. weapon2.ShouldNotBeNull();
  36. weapon1.ShouldBeSameAs(weapon2);
  37. }
  38. [Fact]
  39. public void ScopeDoesNotInterfereWithExternalRequests()
  40. {
  41. kernel.Bind<IWeapon>().To<Sword>().InThreadScope();
  42. IWeapon weapon1 = kernel.Get<IWeapon>();
  43. IWeapon weapon2 = null;
  44. ThreadStart callback = () => weapon2 = kernel.Get<IWeapon>();
  45. var thread = new Thread(callback);
  46. thread.Start();
  47. thread.Join();
  48. weapon1.ShouldNotBeNull();
  49. weapon2.ShouldNotBeNull();
  50. weapon1.ShouldNotBeSameAs(weapon2);
  51. }
  52. [Fact]
  53. public void InstancesActivatedWithinScopeAreDeactivatedAfterThreadIsGarbageCollectedAndCacheIsPruned()
  54. {
  55. kernel.Bind<NotifiesWhenDisposed>().ToSelf().InThreadScope();
  56. var cache = kernel.Components.Get<ICache>();
  57. NotifiesWhenDisposed instance = null;
  58. ThreadStart callback = () => instance = kernel.Get<NotifiesWhenDisposed>();
  59. var thread = new Thread(callback);
  60. thread.Start();
  61. thread.Join();
  62. thread = null;
  63. GC.Collect();
  64. GC.WaitForPendingFinalizers();
  65. cache.Prune();
  66. instance.ShouldNotBeNull();
  67. instance.IsDisposed.ShouldBeTrue();
  68. }
  69. }
  70. }