浏览代码

Prevent NullReferenceException in case of missing Host

Do not throw a NullReferenceException when Host variable is not set.
Ignore the calls to RegisterObject and UnregisterObject instead.
Joerg Rosenkranz 11 年之前
父节点
当前提交
f927c83afe

+ 6 - 2
mcs/class/System.Web/System.Web.Hosting/HostingEnvironment.cs

@@ -160,7 +160,9 @@ namespace System.Web.Hosting {
 		{
 			if (obj == null)
 				throw new ArgumentNullException ("obj");
-			Host.RegisterObject (obj, false);
+
+			if (Host != null)
+				Host.RegisterObject (obj, false);
 		}
 
 		public static void RegisterVirtualPathProvider (VirtualPathProvider virtualPathProvider)
@@ -200,7 +202,9 @@ namespace System.Web.Hosting {
 		{
 			if (obj == null)
 				throw new ArgumentNullException ("obj");
-			Host.UnregisterObject (obj);
+
+			if (Host != null)
+				Host.UnregisterObject (obj);
 		}
 	}
 }

+ 13 - 0
mcs/class/System.Web/Test/System.Web.Hosting/HostingEnvironmentTest.cs

@@ -35,6 +35,10 @@ using System.Web.UI;
 using MonoTests.SystemWeb.Framework;
 
 namespace MonoTests.System.Web.Hosting {
+	public class MyRegisteredObject : IRegisteredObject {
+		public void Stop(bool immediate) {}
+	}
+
 	[TestFixture]
 	public class HostingEnvironmentTest {
 		[Test]
@@ -105,6 +109,15 @@ namespace MonoTests.System.Web.Hosting {
 		{
 			Assert.IsNull (HostingEnvironment.MapPath ("hola"));
 		}
+
+		[Test]
+		public void RegisterAndUnregisterObject ()
+		{
+			var registered = new MyRegisteredObject ();
+
+			HostingEnvironment.RegisterObject (registered);
+			HostingEnvironment.UnregisterObject (registered);
+		}
 	}
 }
 #endif