使用ApplicationHost.CreateApplicationHost()创建ASP.NET发布,同时从其他位置加载程序集

kd3sttzy  于 2023-02-14  发布在  .NET
关注(0)|答案(1)|浏览(162)

我尝试使用CreateApplicationHost为一个简单的Web服务器创建一个Asp.NET应用程序主机,但是当它尝试创建编组对象的示例时,我得到了一个System.IO.FileNotFoundException

host = (MyMarshaller)ApplicationHost.CreateApplicationHost((MyMarshaller), virtualDir, physicalDir);

我相信这个错误是因为它找不到包含类MyMarshaller的程序集-如果我把这个程序集放在physicalDir的bin目录中,那么一切都正常,但是我不想这样做(我也不想把我的程序集放在GAC中)。
有什么方法可以控制CreateApplicationHost在哪里查找我的程序集吗?(注意,MyMarshaller类与上面的代码行包含在同一个程序集中)

krugob8w

krugob8w1#

简短的回答是,这是不可能做到的,但是Cassini源代码揭示了一个替代解决方案。

    • 更新**

上面的链接不再起作用,但是CodePlex上的CassiniDev project看起来非常接近(可能是衍生作品),并且包含相同的解决方案。
解决方案是避免使用CreateApplicationHost,而是"自己动手"-在本例中,使用反射创建内部"BuildManagerHost"类型的示例并调用"RegisterAssembly",如下所示

/// <remarks>
/// This is Dmitry's hack to enable running outside of GAC.
/// There are some errors being thrown when running in proc
/// </remarks>
private object CreateWorkerAppDomainWithHost(string virtualPath, string physicalPath, Type hostType,int port)
{
    // create BuildManagerHost in the worker app domain
    //ApplicationManager appManager = ApplicationManager.GetApplicationManager();
    Type buildManagerHostType = typeof(HttpRuntime).Assembly.GetType("System.Web.Compilation.BuildManagerHost");
    IRegisteredObject buildManagerHost = ApplicationManager.CreateObject(_appId, buildManagerHostType, virtualPath,
                                                                  physicalPath, false);
    
    // call BuildManagerHost.RegisterAssembly to make Host type loadable in the worker app domain
    buildManagerHostType.InvokeMember("RegisterAssembly",
                                      BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic,
                                      null,
                                      buildManagerHost,
                                      new object[] { hostType.Assembly.FullName, hostType.Assembly.Location });
    
    // create Host in the worker app domain
    // FIXME: getting FileLoadException Could not load file or assembly 'WebDev.WebServer20, Version=4.0.1.6, Culture=neutral, PublicKeyToken=f7f6e0b4240c7c27' or one of its dependencies. Failed to grant permission to execute. (Exception from HRESULT: 0x80131418)
    // when running dnoa 3.4 samples - webdev is registering trust somewhere that we are not
    return ApplicationManager.CreateObject(_appId, hostType, virtualPath, physicalPath, false);
}

相关问题