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

Language C# Lines 83
MD5 Hash 829ad83fb809815a54b9b8e114d512f8
Repository https://github.com/developingchris/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
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();
		}
	}
}
Back to Top