使用 ApplicationHost.CreateApplicationHost() 创建一个 Asp.Net 帖子,同时从另一个位置加载程序集

Jus*_*tin 4 asp.net applicationhost

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

host = (MyMarshaller)ApplicationHost.CreateApplicationHost((MyMarshaller), virtualDir, physicalDir);
Run Code Online (Sandbox Code Playgroud)

我相信这个错误是因为它找不到包含类 MyMarshaller 的程序集 - 如果我将此程序集放在 physicalDir 的 bin 目录中,那么一切正常,但是我不想这样做(我也不想或者将我的程序集放在 GAC 中)。

有什么方法可以控制 CreateApplicationHost 在何处查找我的程序集?(请注意,MyMarshaller该类与上述代码行位于同一程序集中)

Jus*_*tin 5

简短的回答是不可能做到这一点,但是卡西尼号的消息来源透露了一个替代解决方案。


更新

上面的链接不再有效,但是CodePlex 上的CassiniDev 项目似乎非常接近(可能是衍生作品)并且包含相同的解决方案。

解决方案是避免使用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);
}
Run Code Online (Sandbox Code Playgroud)