使用GAC和bin加载WEB应用程序域,被加载的对象必须继承MarshalByRefObject
代码如下:
public class Intelligencer : MarshalByRefObject { public string Report() { AppDomain appDomain = AppDomain.CurrentDomain; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Domain ID:{0}\r\n",appDomain.Id); sb.AppendFormat("VirtualPath:{0}\r\n",HostingEnvironment.ApplicationVirtualPath); sb.AppendFormat("PhysicalOath:{0}\r\n", HostingEnvironment.ApplicationPhysicalPath); return sb.ToString(); } }
static void TestHosting() { Intelligencer intell = ApplicationHost.CreateApplicationHost(typeof(Intelligencer), "/", Environment.CurrentDirectory) as Intelligencer; Console.WriteLine("Current Domain ID:{0}\r\n",AppDomain.CurrentDomain.Id); Console.WriteLine(intell.Report()); }
如果调用的对象继承MarshalByRefObject同时也实现IRegisteredObject 我们可以用ApplicationManager来加载应用程序域
public class Intelligencer : MarshalByRefObject, IRegisteredObject { public string Report() { AppDomain appDomain = AppDomain.CurrentDomain; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Domain ID:{0}\r\n",appDomain.Id); sb.AppendFormat("VirtualPath:{0}\r\n",HostingEnvironment.ApplicationVirtualPath); sb.AppendFormat("PhysicalOath:{0}\r\n", HostingEnvironment.ApplicationPhysicalPath); return sb.ToString(); } public void Stop(bool immediate) { HostingEnvironment.UnregisterObject(this); } }
调用方式
static void TestHosting() { Intelligencer intell = CreateWorkerAppDomainWithHost(typeof(Intelligencer), "/", Environment.CurrentDirectory) as Intelligencer; Console.WriteLine("Current Domain ID:{0}\r\n",AppDomain.CurrentDomain.Id); Console.WriteLine(intell.Report()); } static object CreateWorkerAppDomainWithHost(Type hostType,string virtualPath, string physicalPath) { string uniqueAppString = string.Concat(virtualPath, physicalPath).ToLowerInvariant(); string appid = (uniqueAppString.GetHashCode()).ToString("X", CultureInfo.InvariantCulture); var appmanager=ApplicationManager.GetApplicationManager(); var buildManagerHostType = typeof(HttpRuntime).Assembly.GetType("System.Web.Compilation.BuildManagerHost"); var buildManagerHost = appmanager.CreateObject(appid, buildManagerHostType, virtualPath, physicalPath, false); buildManagerHostType.InvokeMember("RegisterAssembly", BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic, null, buildManagerHost, new object[] {hostType.Assembly.FullName,hostType.Assembly.Location }); return appmanager.CreateObject(appid,hostType,virtualPath,physicalPath,false); }