ninject /src/Ninject.Tests/Integration/RequestScopeTests.cs

Language C# Lines 100
MD5 Hash 32c8b0049e62a09fc401dfd42c19be35
Repository https://github.com/daniyord/ninject.git View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
using System;
using System.IO;
using System.Web;
using Ninject.Activation.Caching;
using Ninject.Infrastructure.Disposal;
using Ninject.Tests.Fakes;
using Xunit;
using Xunit.Should;

namespace Ninject.Tests.Integration.RequestScopeTests
{
	public class RequestScopeContext
	{
		protected readonly StandardKernel kernel;

		public RequestScopeContext()
		{
			var settings = new NinjectSettings { CachePruningInterval = TimeSpan.MaxValue };
			kernel = new StandardKernel(settings);
		}

		public void BeginNewFakeWebRequest()
		{
			HttpContext.Current = GetFakeHttpContext();
		}

		public HttpContext GetFakeHttpContext()
		{
			var request = new HttpRequest("index.html", "http://example.org/index.html", String.Empty);
			var response = new HttpResponse(new StringWriter());
			return new HttpContext(request, response);
		}
	}

	public class WhenServiceIsBoundWithRequestScope : RequestScopeContext
	{
		[Fact]
		public void InstancesAreReusedWithinSameHttpContext()
		{
			kernel.Bind<IWeapon>().To<Sword>().InRequestScope();

			BeginNewFakeWebRequest();

			var weapon1 = kernel.Get<IWeapon>();
			var weapon2 = kernel.Get<IWeapon>();

			weapon1.ShouldBeSameAs(weapon2);

			BeginNewFakeWebRequest();

			GC.Collect();
			GC.WaitForPendingFinalizers();

			var weapon3 = kernel.Get<IWeapon>();

			weapon3.ShouldNotBeSameAs(weapon1);
			weapon3.ShouldNotBeSameAs(weapon2);
		}

		[Fact]
		public void InstancesAreDisposedWhenRequestEndsAndCacheIsPruned()
		{
			kernel.Bind<INotifyWhenDisposed>().To<NotifiesWhenDisposed>().InRequestScope();
			var cache = kernel.Components.Get<ICache>();

			BeginNewFakeWebRequest();

			var instance = kernel.Get<INotifyWhenDisposed>();

			instance.ShouldNotBeNull();
			instance.ShouldBeInstanceOf<NotifiesWhenDisposed>();

			BeginNewFakeWebRequest();

			GC.Collect();
			GC.WaitForPendingFinalizers();

			cache.Prune();

			instance.IsDisposed.ShouldBeTrue();
		}

		[Fact]
		public void InstancesAreDisposedViaOnePerRequestModule()
		{
			kernel.Bind<INotifyWhenDisposed>().To<NotifiesWhenDisposed>().InRequestScope();

			BeginNewFakeWebRequest();

			var instance = kernel.Get<INotifyWhenDisposed>();

			instance.ShouldNotBeNull();
			instance.ShouldBeInstanceOf<NotifiesWhenDisposed>();

			OnePerRequestModule.DeactivateInstancesForCurrentHttpRequest();

			instance.IsDisposed.ShouldBeTrue();
		}
	}
}
Back to Top